1.设置指定列单元格的前景色
//获取TableColumn对象TableColumn tableColumn = jTable.getColumn("月薪");//初始化Table的渲染器DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer();//设置单元格的前景色cellRenderer.setForeground(Color.red);//将渲染器设置到获取到的列tableColumn.setCellRenderer(cellRenderer);
2.设置指定单元格的背景色
//获取TableColumn对象
TableColumn departmentColumn = jTable.getColumn("部门");//重新申明渲染器DefaultTableCellRenderer cellRenderer2 = new DefaultTableCellRenderer();//设置单元格的背景色cellRenderer2.setBackground(Color.blue);//将渲染器放入departmentColumn.setCellRenderer(cellRenderer2);3.设置不能拖动一列
jTable.getTableHeader().setReorderingAllowed(false);
4.设置每一列的大小不能改变
jTable.getTableHeader().setResizingAllowed(false);
5.设置每一行颜色交替
DefaultTableCellRenderer cellRenderer3 = new DefaultTableCellRenderer(){
public Component getTableCellRendererComponent(JTable arg0,Object arg1, boolean arg2, boolean arg3, int arg4, int arg5) {
// TODO Auto-generated method stubif(arg4%2 == 0){ this.setBackground(Color.pink);}else { this.setBackground(Color.white);}return super.getTableCellRendererComponent(arg0, arg1, arg2, arg3, arg4, arg5);}};//每一格设置渲染器for(int i=0; i<jTable.getColumnCount(); i++){ TableColumn tableColumn = jTable.getColumn(jTable.getColumnName(i));tableColumn.setCellRenderer(cellRenderer3);}6.在表格中创建下拉框
JComboBox jComboBox = new JComboBox();
jComboBox.addItem("人事部");jComboBox.addItem("经理部");jComboBox.addItem("开发部");jComboBox.addItem("财务部");//获取列TableColumn tableColumn = jTable.getColumn("部门");//生成表格编辑器DefaultCellEditor defaultCellEditor = new DefaultCellEditor(jComboBox);//设置表格编辑器tableColumn.setCellEditor(defaultCellEditor);7.设置单元格中的对齐方式
DefaultTableCellRenderer cellRenderer3 = new DefaultTableCellRenderer();cellRenderer3.setHorizontalAlignment(JLabel.CENTER);for (int i = 0; i < jTable.getColumnCount(); i++) { TableColumn tc = jTable.getColumn(jTable.getColumnName(i));tc.setCellRenderer(cellRenderer3);}8.在对数据进行添加时,可以使用DefaultTableModel类的对象的addRow方法直接添加到TalbeModel中,当然,对应数据库也要进行操作。
注意!在为JTable指定样式的时候,后面定义的会覆盖前面定的(例如:5对其他样式就有覆盖作用,如果5放在后面会将前面所有的样式都覆盖掉)