如何在Java中显示/隐藏JTable的表头?
JTable是JComponent类的子类,用于显示复杂的数据结构。JTable可以遵循模型-视图-控制器(MVC)设计模式来显示行列数据。DefaultTableModel类是AbstractTableModel的子类,可用于动态地向JTable添加行和列。DefaultTableCellRenderer类可以扩展JLabel类,用于在JTable单元格中添加图像、彩色文本等。我们可以通过取消选中JCheckBox来隐藏JTable的表头,并通过点击JCheckBox来显示JTable的表头。
示例
import java.awt.*; import javax.swing.*; import javax.swing.table.*; public final class JTableHeaderHideTest extends JPanel { private final String[] columnNames = {"String", "Integer", "Boolean"}; private final Object[][] data = {{"Tutorials Point", 100, true}, {"Tutorix", 200, false}, {"Tutorials Point", 300, true}, {"Tutorix", 400, false}}; private final TableModel model = new DefaultTableModel(data, columnNames) { @Override public Class getColumnClass(int column) { return getValueAt(0, column).getClass(); } }; private final JTable table = new JTable(model); private final JScrollPane scrollPane = new JScrollPane(table); public JTableHeaderHideTest() { super(new BorderLayout()); add(scrollPane); JCheckBox check = new JCheckBox("JTableHeader visible: ", true); check.addActionListener(ae -> { JCheckBox cb = (JCheckBox) ae.getSource(); scrollPane.getColumnHeader().setVisible(cb.isSelected()); scrollPane.revalidate(); }); add(check, BorderLayout.NORTH); } public static void main(String[] args) { JFrame frame = new JFrame("JTableHeaderHide Test"); frame.setSize(375, 250); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new JTableHeaderHideTest()); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
输出
显示表头
隐藏表头
广告