Code不会在ide文本字段中输出"Works"消息。如何使程序在ide的文本中输出我的消息?非常感谢。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class test extends JFrame {
private JButton button1;
public test() {
JFrame frame = new JFrame("Test Program");
JPanel panel = new JPanel();
JButton button1 = new JButton("Click me PLEASE!");
panel.setBackground(Color.red);
panel.add(button1);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(800, 800);
Listener1 listen = new Listener1();
button1.addActionListener(listen);
}
public static void main(String[] args) {
new test();
}
private class Listener1 implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == button1) {
System.out.println("Works!");
}
}
}
您正在比较的button1
实例不是触发事件的button1
实例。。。
基本上,你是在跟踪你的变量。。。
// Declare instance variable here...
private JButton button1;
public test() {
//...
// Redeclared as local variable here
JButton button1 = new JButton("Click me PLEASE!");
如果添加。。。
System.out.println("button1 = " + button1);
给你Listener1
,你会发现它是null
删除本地声明。。。
button1 = new JButton("Click me PLEASE!");