【问题标题】:ActionListener not working on JButtonActionListener 在 JButton 上不起作用
【发布时间】:2015-07-06 16:20:49
【问题描述】:

我已经编写了一个代码来显示三个面板中的三个按钮 网格布局的框架。 目标是 - 单击按钮时更改按钮的颜色 - 最初他们三个都是黑色的

代码运行完美,只是按钮的颜色没有改变
点击。 谁能指出问题或调试它。

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);
    }
}

【问题讨论】:

  • 我认为这是一个错字。在第二个if 中将b1.setBackground(Color.YELLOW); 更改为b2.setBackground(Color.YELLOW);...
  • 知道了,您重新声明了按钮和面板,它们在全球范围内都是空的。huhu 知道了

标签: java swing jbutton actionlistener


【解决方案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)
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多