Swing 之 JTable 使表头标题和表格内容居中

封装的DButil.java,负责数据库连接:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ethan.util;



import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class DBUtil {
    
    private static final String url = "jdbc:mysql://localhost:3306/test";
    private static final String username = "root";
    private static final String password = "";
    
   
    //private DBUtil dbUtil = null;
    
    private DBUtil() {
        
    }
    
    
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public static Connection getConn() {
        try {
            return  DriverManager.getConnection(url,username,password);
            
        } catch (SQLException ex) {
            Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public static PreparedStatement getPstmt(Connection conn, String sql) {
        try {
            return conn.prepareStatement(sql);
        } catch (SQLException ex) {
            Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }
    
    public static ResultSet getRs(PreparedStatement pstmt) {
        try {
            return pstmt.executeQuery();
        } catch (SQLException ex) {
            Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }
    
    public static void close(Connection conn,Statement stmt, ResultSet rs) {
        if(conn!=null) {
            try {
                conn.close();
                conn = null;
            } catch (SQLException ex) {
                Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if(stmt!=null) {
                    try {
                        stmt.close();
                        stmt = null;
                    } catch (SQLException ex) {
                        Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);
                    } finally {
                        if(rs!=null) {
                            try {
                                rs.close();
                                rs = null;
                            } catch (SQLException ex) {
                                Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);
                            } finally {
                                conn = null;
                                stmt = null;
                            }
                            
                        }
                        
                    }
                    
                } 
            }
        }
    }
}

下边是采用netbeans 新建的JFrame, 拖拉控件到面板上:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jtable;

import com.ethan.util.DBUtil;
import java.awt.Color;
import java.awt.Dimension;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author Administrator
 */
public class TestJTableFrame extends javax.swing.JFrame {

    /**
     * Creates new form TestJTableFrame
     */
    public TestJTableFrame() {
         initComponents();
         setTitle("使用数组填充数据");
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        
        //getContentPane().add(scrollPane,BorderLayout.CENTER);
        
        String sql = "select * from student";
        Connection conn = DBUtil.getConn();
        PreparedStatement pstmt = DBUtil.getPstmt(conn, sql);
        ResultSet rs = DBUtil.getRs(pstmt);
        ResultSetMetaData data;
        
        //二维数组的维数写死了
         String[][] values = new String[3][3];
         String[] columns = null;
        try {
            data = rs.getMetaData();
            columns = new String[data.getColumnCount()];
            for(int i=0;i columnClass) {
//            DefaultTableCellRenderer cr = (DefaultTableCellRenderer) super.getDefaultRenderer(columnClass);
//            
//            cr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
//            return cr;
//        }
        
        //单元格可编辑
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // 
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(15, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(15, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// 

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TestJTableFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestJTableFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestJTableFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestJTableFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TestJTableFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration
}


//如果自己重写  public TableCellRenderer getDefaultRenderer(Class columnClass) 就会出一下异常。
//请高手多多指教了!
/*
 * Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JTable$BooleanRenderer cannot be cast to javax.swing.table.DefaultTableCellRenderer
	at jtable.TestJTableFrame$CusJTable.getDefaultRenderer(TestJTableFrame.java:125)
	at javax.swing.plaf.synth.SynthTableUI.installRendererIfPossible(SynthTableUI.java:102)
	at javax.swing.plaf.synth.SynthTableUI.installDefaults(SynthTableUI.java:93)
	at javax.swing.plaf.basic.BasicTableUI.installUI(BasicTableUI.java:1351)
	at javax.swing.JComponent.setUI(JComponent.java:662)
	at javax.swing.JTable.setUI(JTable.java:3574)
 */


你可能感兴趣的:(java)