在动作侦听器侦听事件后,Java gui不会打印

时间:2014-04-23 03:41:12

标签: java user-interface

代码不会在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!");
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

您要比较的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!");