gpt4 book ai didi

java - ActionEvent不会出现

转载 作者:行者123 更新时间:2023-12-01 11:48:36 24 4
gpt4 key购买 nike

我的程序有问题。这是我的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;`

public class click_rep extends JFrame{`

public click_rep(){

super("CLICK");
final JButton btn1 = new JButton("CLICK HERE");
final JLabel label = new JLabel();
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(btn1);
setSize(315,120);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

btn1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){
try{
String command = e.getActionCommand();
if (command.equals(btn1)){
label.setText("CLICK");
setVisible(true);
}
}catch(Exception e1){
e1.printStackTrace();
}

}


});

}

public static void main(String[] a){
click_rep cp = new click_rep();
}

}

我的问题是 ActionEvent 不会出现。我该怎么做才能让 ActionEvent 出现?

希望有人能帮助我。感谢您的帮助。

最佳答案

仔细看看这个...

String command = e.getActionCommand();
if (command.equals(btn1)){

command 是一个 Stringbtn1 是一个 JButton,它们什么时候可能是 等于

有几种方法可以修复它,例如,您可以这样做......

if ("CLICK HERE".equals(command)) {

或者类似的东西...

if (e.getSource() == btn1) {

但我更喜欢第一个...

但是,由于 ActionListener 是注册到 btn1 的烦人监听器,因此事件源绝不能是 btn1 以外的任何内容,所以你可以简单地做这样的事情......

btn1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){
label.setText("CLICK");
// Not sure what this is meant for, as the component
// must already be visible in order for the user to
// activate the button...
setVisible(true);
}

});

关于java - ActionEvent不会出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28954380/

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