gpt4 book ai didi

Java鼠标监听器

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:42:19 24 4
gpt4 key购买 nike

我如何编写一个鼠标监听器,它会对按下 JFrame 中的任何对象或某个特定对象使用react?

这是我的鼠标监听器 -

class mouse extends MouseAdapter
{
public void mousePressed(MouseEvent event)
{
yearLabel.setText("nu");
}
}

最佳答案

您可以通过 Toolkit.getDefaultToolkit().addAWTEventListener(listener,mask) 添加全局鼠标监听器

举个例子

public class SwingTest{
public static void main(String[] args) {
JPanel mainPanel = new JPanel();
mainPanel.add(new JButton("button"));
final JLabel label = new JLabel("label");
mainPanel.add(label);

showFrame("", mainPanel);

Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
public void eventDispatched(AWTEvent event) {
if(event instanceof MouseEvent){
MouseEvent evt = (MouseEvent)event;
if(evt.getID() == MouseEvent.MOUSE_CLICKED){
label.setText("mouse clicked at: " + evt.getPoint());
}
}
}
}, AWTEvent.MOUSE_EVENT_MASK);
}

public static JFrame showFrame(String title, Component component) {
JFrame frame = new JFrame();
frame.setTitle(title);
frame.getContentPane().add(component, BorderLayout.CENTER);
frame.setSize(900, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
return frame;
}
}

关于Java鼠标监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6708436/

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