Consider a javax.swing.JPanel
with the following as its MouseListener
new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
var count = e.getClickCount();
switch (count) {
case 1 -> Helper.sop("single count");
case 2 -> Helper.sop("double count");
default -> Helper.sop("more than double count %d".formatted(count));
}
}
}
Upon double-clicking, I am getting the following puzzling output
single count
double count
instead of the expected
double count
Apparently, during a double click, a single click precedes the said double click. Why is this so?
rough.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.UUID;
public class rough {
public static void main(String[] args) throws Exception {
//Helper.sop=System.out.println
//Helper.launch=launch a JPanel in a JFrame (new,pack,EXIT_ON_CLOSE,<Screen_Size,UUIDTitle,SystemLAF,EDTThread)
JPanel pn = new JPanel();
pn.setPreferredSize(new Dimension(500, 500));
///////////////////THIS IS ALL THAT MATTERS HERE//////////////////////
pn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
var count = e.getClickCount();
switch (count) {
case 1 -> Helper.sop("single count");
case 2 -> Helper.sop("double count");
default -> Helper.sop("more than double count %d".formatted(count));
}
}
});
/////////////////////////////////////////////////////////////////////
Helper.launch(pn);
}
private static class Helper {
static public int frameNo = 0;
public static void sop(Object o) {
System.out.println(o);
}
public static void launch(JPanel pnMain, String frameTitle, String lafClassName) {
try {
UIManager.setLookAndFeel(lafClassName);
f.sop("set laf to " + lafClassName);
} catch (Exception e) {
System.err.println("err: couldn't apply laf");
}
final var screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final var pnSize = pnMain.getPreferredSize();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame(frameTitle);
if (pnSize.width > screenSize.width || pnSize.getHeight() > screenSize.getHeight())
frame.setPreferredSize(new Dimension((int) (screenSize.width * 0.75), (int) (0.75 * screenSize.height)));
frame.setContentPane(pnMain);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
public static void launch(JPanel pnMain, String frameTitle) {
launch(pnMain, frameTitle, UIManager.getSystemLookAndFeelClassName());
}
public static void launch(JPanel pnMain) {
String title = "Frame no: " + ++frameNo + "\t (" + UUID.randomUUID() + ")";
launch(pnMain, title);
}
}
}
Env:
openjdk 15.0.2 2021-01-19
OpenJDK Runtime Environment (build 15.0.2+7-27)
OpenJDK 64-Bit Server VM (build 15.0.2+7-27, mixed mode, sharing)
Windows 10