双击 Java 中 JTable 上的侦听器

我很好奇如何仅在双击其中的行时才调用重写的方法。现在,下面的代码片段实现了一键操作或事件箭头键,以浏览人员列表并进行相应调整。我试图做的是类似的事情,就像我一次点击一样,但这次如果并且只有当一行被双击时,才会改变,否则不会发生任何事情。如何执行此操作:(valueChangedJTableJLabeldto

   class ListDataUI {

    public void addListSelectionListener(ListSelectionListener listSelectionListener) {
            summaryTable.getSelectionModel().addListSelectionListener(listSelectionListener);

 public T getSelectedDTO() {
        final int selectedRowIndex = summaryTable.getSelectedRow();
        if (selectedRowIndex != -1) {
            return data.get(summaryTable.convertRowIndexToModel(selectedRowIndex));
        } else {
            return null;
        }
    }
        }
    }




    class MainMenu extends javax.swing.JFrame {
    private void initListeners() {
    searchTable.addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                AcademicDTO dto = (AcademicDTO) searchTable.getSelectedDTO();
                acImgLabel.setIcon(new ImageIcon());
                label_name.setText(dto.getTitle() + " " + dto.getForename() + " " + dto.getSurname());
                label_role.setText("Role: " + dto.getRole());
                label_phone.setText("Phone: " + dto.getPhone());
                label_room.setText("Room: " + dto.getRoom());
                label_hours.setText("Hours: " + dto.getHours());
                label_mobile.setText("Mobile: " + dto.getMobile());
                if (dto.getImage() != null) {
                    acImgLabel.setIcon(new ImageIcon(dto.getImage()));
                }
            }
        }
    });
}

}


 private void initListeners() {
    contactTable.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            ContactDTO dto = (ContactDTO) contactTable.getSelectedDTO();
            if (e.getClickCount() == 2) {
                System.out.println(dto.getForename());
            } else {
            }

        }
    });
}

不确定上面的其余部分...


答案 1

试试这个:

mytable.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent mouseEvent) {
        JTable table =(JTable) mouseEvent.getSource();
        Point point = mouseEvent.getPoint();
        int row = table.rowAtPoint(point);
        if (mouseEvent.getClickCount() == 2 && table.getSelectedRow() != -1) {
            // your valueChanged overridden method 
        }
    }
});

答案 2

将事件处理程序的代码重定位到主机类中的私有方法中,然后实现或扩展,然后在此处调用私有方法。第一步(即创建私有方法可帮助您从多个事件处理程序调用相同的逻辑)。MouseListenerMouseAdapter

检测双击变得容易通过调用MouseHandlerMouseEvent.getClickCount()


推荐