简体   繁体   中英

mouse double click is not working

I have written this java code to detect the double click of left button on mouse, but this code is not working please help.

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class B extends MouseAdapter {

    JFrame frame = new JFrame();
    Object rows[][] = new Object[5][3];
    String colums[] = {"A","B","C"};
    JTable table = new JTable(rows,colums);
    JScrollPane scroll = new JScrollPane(table);

    public static void main(String arg[]) {
        new B();
    }

    B() {
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        table.addMouseListener(this);
        frame.add(scroll);
        frame.setVisible(true);
    }

    public void mouseClicked(MouseEvent clicked) {
        if(clicked.getSource()==table && clicked.getButton()==1 && clicked.getClickCount()==2)
            System.out.println("Left Double Click");
    }
}
  1. Your example won't compile
  2. You should be using SwingUtilities.isLeftMouseButton(clicked) instead of clicked.getButton()==1
  3. The table may be consuming the MouseEvent and installing the cell editor before your MouseListener is notified.
  4. If you use table.setFillsViewportHeight(true); you can double click outside of the rows/columns successfully

You can change the table's CellEditor s to ignore the MouseEvent (or change the number of clicks required), this will allow you MouseListener to pick up the double clicks, but will also increase your work load, as you will need to supply a CellEditor for each column Class type

    TableCellEditor editor = new DefaultCellEditor(new JTextField(10)) {

        @Override
        public boolean isCellEditable(EventObject anEvent) {
            boolean editable = false;
            if (!(anEvent instanceof MouseEvent)) {
                editable = super.isCellEditable(anEvent);
            }
            return editable;
        }

    };

    table.setDefaultEditor(Object.class, editor);

Without more context, is difficult to know what else to suggest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM