Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีตรวจสอบว่า JTable มีเซลล์ว่างหรือไม่ใน Java


JTable เป็นคลาสย่อยของคลาส JComponent ใช้สำหรับแสดงโครงสร้างข้อมูลที่ซับซ้อน JTable สามารถปฏิบัติตามรูปแบบการออกแบบ Model View Controller (MVC) เพื่อแสดงข้อมูลใน แถวและคอลัมน์ JTable จะสร้างอินเทอร์เฟซ TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener และ RowSorterListener

เราสามารถตรวจสอบว่าเซลล์ของ JTable ว่างหรือไม่โดยการใช้เมธอด getValueAt() ของคลาส JTable เมื่อคลิกที่ปุ่ม "Click Here" จะสร้างเหตุการณ์การกระทำ (action event) และแสดงข้อความป๊อปอัปว่า "Field is Empty" ให้ผู้ใช้เห็น

ตัวอย่าง

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();
    }
}

ผลลัพธ์

วิธีตรวจสอบว่า JTable มีเซลล์ว่างหรือไม่ใน Java