ActionListener没有在JButton上工作

时间:2015-07-06 16:20:49

标签: java swing jbutton actionlistener

我编写了一个代码,在三个面板上显示三个按钮 框架与网格布局。 目标是   - 单击按钮时更改按钮的颜色   - 最初所有3个都是黑色

代码运行完美,但按钮的颜色不会改变 单击。 任何人都可以指出问题或调试它。

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class gui extends JFrame implements ActionListener {

    JPanel p1, p2, p3;
    JButton b1, b2, b3;

    public gui() {
        setLayout(new GridLayout(3, 1));
        JPanel p1 = new JPanel(new GridLayout(1, 1));
        JPanel p2 = new JPanel(new GridLayout(1, 1));
        JPanel p3 = new JPanel(new GridLayout(1, 1));
        JButton b1 = new JButton();
        JButton b2 = new JButton();
        JButton b3 = new JButton();
        b1.setBackground(Color.BLACK);
        b2.setBackground(Color.BLACK);
        b3.setBackground(Color.BLACK);
        b1.addActionListener(this);
        p1.add(b1);
        b2.addActionListener(this);
        p2.add(b2);
        b3.addActionListener(this);
        p3.add(b3);
        add(p1);
        add(p2);
        add(p3);
    }

    public void actionPerformed(ActionEvent e) //function to handle click
    {
        if (e.getSource() == b1) {
            b1.setBackground(Color.RED);
        } else if (e.getSource() == b2) {
            b1.setBackground(Color.YELLOW);
        } else if (e.getSource() == b3) {
            b3.setBackground(Color.BLUE);
        }
    }

    public static void main(String[] args) {
        gui ob1 = new gui();
        ob1.setSize(1000, 500);
        ob1.setLocation(100, 100);
        ob1.setVisible(true);
        ob1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

1 个答案:

答案 0 :(得分:1)

  1. 您必须使用[同样适用于面板]

    来初始化按钮
     b1 = new JButton();
     b2 = new JButton();
     b3 = new JButton();
    

    因为您正在创建隐藏全局变量的局部变量

    JButton b1 = new JButton();//local variables
    JButton b2 = new JButton();
    JButton b3 = new JButton();
    
  2. 在第二个if条件中,您必须更改b2的颜色而不是b1

         else if(e.getSource()==b2){
    
                //b1.setBackground(Color.YELLOW);
                b2.setBackground(Color.YELLOW);
    
                }
    
  3. 始终使用.equals()代替==来比较对象

       e.getSource().equals(b1)