我的程序出了点问题。下面是我的代码:
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出现呢?
希望有人能帮我。谢谢你的帮助。
发布于 2015-03-10 08:54:26
仔细看看这个。
String command = e.getActionCommand();
if (command.equals(btn1)){command是String,btn1是JButton,它们什么时候可能成为equal
有几种方法可以修复它,例如,可以这样做……
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);
}
});https://stackoverflow.com/questions/28954380
复制相似问题