如何在 Java 中验证 JTable 是否有空单元格?
awtjavaobject oriented programmingprogrammingswing
JTable 是 JComponent 类的子类,用于显示复杂的数据结构。JTable 可以遵循 Model View Controller (MVC) 设计模式,以 行和列 显示数据。JTable 将生成 TableModelListener、TableColumnModelListener、ListSelectionListener、CellEditorListener 和 RowSorterListener 接口。
我们可以通过实现 JTable 类的 getValueAt() 方法来验证 JTable 单元格是否为空。如果我们点击"单击此处"按钮,它将生成一个动作事件并向用户显示一个弹出消息,如"字段为空"。
示例
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class JTableEmptyValidateTest extends JFrame { private JPanel panel; private JTable table; private JButton button; String[] columnNames = new String[] {"Student 1", "Student 2"}; String[][] dataValues = new String[][] {{"95", "100"}, {"", "85"}, {"80", "100"}}; public JTableEmptyValidateTest() { setTitle("Empty Validation Table"); panel = new JPanel(); table = new JTable(); TableModel model = new myTableModel(); table.setModel(model); panel.add(new JScrollPane(table)); button = new JButton("Click Here"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if(validCheck()) { JOptionPane.showMessageDialog(null,"Field is filled up"); } else { JOptionPane.showMessageDialog(null, "Field is empty"); } } }); add(panel, BorderLayout.CENTER); add(button, BorderLayout.SOUTH); setSize(470, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public boolean validCheck() { if(table.getCellEditor()!= null) { table.getCellEditor().stopCellEditing(); } for(int i=0; i < table.getRowCount(); i++) { for(int j=0; j < table.getColumnCount(); j++) { String value = table.getValueAt(i,j).toString(); if(value.trim().length() == 0) { return false; } } } return true; } class myTableModel extends DefaultTableModel { myTableModel() { super(dataValues, columnNames); } public boolean isCellEditable(int row, int cols) { return true; } } public static void main(String args[]) { new JTableEmptyValidateTest(); } }