JTable là một lớp con của JComponent dùng để hiển thị các cấu trúc dữ liệu phức tạp. JTable có thể tuân theo mô hình thiết kế Model View Controller (MVC) để hiển thị dữ liệu theo hàng và cột. Một JTable sẽ tạo ra các interface TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener và RowSorterListener.
Chúng ta có thể kiểm tra xem ô của JTable có trống hay không bằng cách triển khai phương thức getValueAt() của lớp JTable. Khi nhấn nút "Click Here", một sự kiện hành động sẽ được tạo ra và hiển thị thông báo popup như "Field is Empty" cho người dùng.
Ví dụ
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();
}
}
Kết quả
