gpt4 book ai didi

Java Swing 事件

转载 作者:行者123 更新时间:2023-11-29 06:23:26 26 4
gpt4 key购买 nike

我想知道应该如何实现一个事件,该事件将在按下按钮时执行某些操作,并在释放按钮时停止执行该操作

我尝试为这种方法添加 MouseListerner。问题是它会识别出我按下了按钮。但不是它是哪个按钮。所以想知道应该如何编写它才能知道我按下了哪个按钮。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;


public class Main extends JFrame implements MouseListener, ActionListener{

private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel(new GridLayout(4,4));



public Main() {
setSize(300,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new BorderLayout());
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.CENTER);

String[] buttonNamn = {"1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};

for(int i=0;i<buttonNamn.length;i++) {
JButton button = new JButton(buttonNamn[i]);
panel2.add(button);
button.addMouseListener(this);
button.addActionListener(this);
}

}
public static void createGUI() {
new Main();
}

public static void main(String[] args) {

createGUI();
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub

}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub

}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub

}
@Override
public void mousePressed(MouseEvent arg0) {
System.out.println("Pressed");

}
@Override
public void mouseReleased(MouseEvent arg0) {
System.out.println("Relased");


}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("1")) {
System.out.println("Foo 1");
}
else if(e.getActionCommand().equals("2")){
System.out.println("Foo 2");
}
}
}

最佳答案

您将需要 invokeLater,如下所述:Java: mytextarea.setText("hello") + Thread.sleep(1000) = strange result否则您的操作将阻塞 UI 线程

关于Java Swing 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2048495/

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