我有一个带有鼠标侦听器的JPane,该侦听器检查mouseEntered和mouseExited,这与将鼠标聚焦到窗格上的按钮并触发mouseExited事件这一事实截然不同。是否有一个使JButton不占据鼠标焦点的设置?
答案 0 :(得分:1)
在这种情况下,我不需要专门修改重点。我也不熟悉JPane,所以我以为您的意思是JPanel。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FocusDemo {
private JPanel panel;
private JButton button1;
JFrame frame = new JFrame("TempWindow");
private FocusDemo() {
panel = new JPanel();
button1 = new JButton("Button");
button1.addActionListener((ae) -> System.out.println("button pressed"));
panel.add(button1);
MyMouseListener ml = new MyMouseListener();
panel.addMouseListener(ml);
panel.addMouseMotionListener(ml);
frame.add(panel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new FocusDemo().start());
}
public void start() {
frame.setLocationRelativeTo(null); // this line set the window in the
// center of the screen
frame.setPreferredSize(new Dimension(500, 500));
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class MyMouseListener extends MouseAdapter {
public void mouseEntered(MouseEvent me) {
System.out.println("mouse entered");
}
public void mouseExited(MouseEvent me) {
System.out.println("mouse exited");
}
}
}