为了JTable在表格单元格中将布尔值渲染为复选框,我们需要告诉表格单元格存储了布尔类型的数据。为此,我们必须TableModel为该JTable组件实现。
TableModel的getColumnClass(int columnIndex)必须返回存储在单元中的数据的类型。当返回该列存储Boolean数据时,将JTable显示一个复选框作为该单元格的默认渲染器或编辑器。
package org.nhooo.example.swing; import javax.swing.*; import javax.swing.table.AbstractTableModel; import java.awt.*; public class JTableBooleanAsCheckbox extends JPanel { public JTableBooleanAsCheckbox() { initializeUI(); } private void initializeUI() { setLayout(new BorderLayout()); setPreferredSize(new Dimension(450, 200)); JTable table = new JTable(new BooleanTableModel()); table.setFillsViewportHeight(true); JScrollPane pane = new JScrollPane(table); add(pane, BorderLayout.CENTER); } public static void showFrame() { JPanel panel = new JTableBooleanAsCheckbox(); panel.setOpaque(true); JFrame frame = new JFrame("JTable Boolean as Checkbox"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JTableBooleanAsCheckbox.showFrame(); } }); } class BooleanTableModel extends AbstractTableModel { String[] columns = {"STUDENT ID", "NAME", "SCORE", "PASSED"}; Object[][] data = { {"S001", "ALICE", 90.00, Boolean.TRUE}, {"S002", "BOB", 45.50, Boolean.FALSE}, {"S003", "CAROL", 60.00, Boolean.FALSE}, {"S004", "IGNASIA", 85.80, Boolean.TRUE}, {"S005", "MALLORY", 75.80, Boolean.TRUE} }; public int getRowCount() { return data.length; } public int getColumnCount() { return columns.length; } public Object getValueAt(int rowIndex, int columnIndex) { return data[rowIndex][columnIndex]; } @Override public String getColumnName(int column) { return columns[column]; } // JTable使用此方法定义默认值 //每个单元格的渲染器或编辑器。例如,如果您有 //布尔数据,它将呈现为复选框。一种 // 数字值右对齐。 @Override public Class<?> getColumnClass(int columnIndex) { return data[0][columnIndex].getClass(); } } }
这是程序的结果: