封装的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<columns.length;i++) { columns[i] = data.getColumnName(i+1); System.out.println(columns[i]); } for(int i=0;i<values.length;i++) { //每一条记录,每一行 if(rs.next()) { //每一列 for( int j=0;j<values[i].length;j++) { //values[i] = {rs.getObject("id").toString(),rs.getObject("sid").toString(),rs.getObject("name").toString()}; values[i][j] = rs.getString(j+1); } } } DBUtil.close(conn, pstmt, rs); } catch (SQLException ex) { Logger.getLogger(ArrayCreateTableFrame.class.getName()) .log(Level.SEVERE, null, ex); } this.setSize(new Dimension(400, 300)); //public Window getOwner() returns the owner of this window setLocationRelativeTo(getOwner()); jTable1 = null; jTable1 = new CusJTable(values,columns); //产生水平滚动条 // jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); jTable1.setSelectionBackground(Color.GREEN); DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中 // tcr.setHorizontalAlignment(JLabel.CENTER); tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样 jTable1.setDefaultRenderer(Object.class, tcr); jTable1.setForeground(Color.RED); jTable1.setRowHeight(50); //jScrollPane1.setViewportView(null); jScrollPane1.setViewportView(jTable1); } private class CusJTable extends JTable { public CusJTable(String[][] values, String[] columns) { super(values, columns); } @Override public JTableHeader getTableHeader() { JTableHeader tableHeader = super.getTableHeader(); tableHeader.setReorderingAllowed(false);//表格列不可移动 DefaultTableCellRenderer hr = (DefaultTableCellRenderer) tableHeader .getDefaultRenderer(); hr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);//列名居中 return tableHeader; } // @Override // public TableCellRenderer getDefaultRenderer(Class<?> 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") // <editor-fold defaultstate="collapsed" desc="Generated Code"> 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(); }// </editor-fold> /** * @param args the command line arguments */ public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * 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); } //</editor-fold> /* * 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) */