gpt4 book ai didi

java - JButton 干扰 JPanel 上的鼠标监听器

转载 作者:行者123 更新时间:2023-12-02 09:48:28 26 4
gpt4 key购买 nike

我有一个带有鼠标监听器的 JPanel,用于检查 mouseEnteredmouseExited,这与鼠标聚焦的事实完全不同到 Pane 上的按钮并触发 mouseExited 事件。

是否有设置可以使按钮不占据鼠标焦点?

最佳答案

在这种情况下,我从来不需要专门修改焦点。我也不熟悉 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");
}
}

}

关于java - JButton 干扰 JPanel 上的鼠标监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56483374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com