Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách phát hiện sự kiện double-click trên hàng JTable trong Java

JTable là một lớp con của JComponent để hiển thị cấu trúc dữ liệu phức tạp. JTable tuân theo Model View Controller (MVC) để hiển thị dữ liệu theo hàng và cột. JTable tạo ra TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener. Chúng ta có thể phát hiện double-click trên JTable bằng MouseAdapter hoặc MouseListener. Đặt getClickCount() = '2' của MouseEvent để phát hiện double-click.

Ví dụ

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

public final class DoublClickJTableRowTest extends JFrame {
    private JTable table;
    private JScrollPane scrollPane;

    public DoublClickJTableRowTest() {
        setTitle("DoublClickJTableRow Test");
        String[] columnNames = {"First Name", "Last Name"};
        Object[][] data = {{"Raja", "Ramesh"}, {"Adithya", "Sai"}, {"Vineet", "Kumar"}, {"Krishna", "Kasyap"}};
        table = new JTable(data, columnNames) {
            public boolean editCellAt(int row, int column, java.util.EventObject e) {
                return false;
            }
        };
        table.setFocusable(false);
        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                if (me.getClickCount() == 2) { // Phát hiện double-click
                    JTable target = (JTable) me.getSource();
                    int row = target.getSelectedRow(); // Chọn hàng
                    int column = target.getSelectedColumn(); // Chọn cột
                    JOptionPane.showMessageDialog(null, table.getValueAt(row, column)); // Lấy giá trị hàng/cột
                }
            }
        });
        scrollPane = new JScrollPane(table);
        add(scrollPane);
        setSize(375, 250);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new DoublClickJTableRowTest();
    }
}

Kết quả

Cách phát hiện sự kiện double-click trên hàng JTable trong Java