gpt4 book ai didi

java - ActionListener 不适用于 JButton

转载 作者:行者123 更新时间:2023-12-01 11:20:45 26 4
gpt4 key购买 nike

我编写了一个代码来在三个面板中显示三个按钮具有网格布局的框架。目标是 - 单击按钮时更改按钮的颜色 - 最初 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. 您必须使用[同样适用于面板]来初始化按钮

     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)

关于java - ActionListener 不适用于 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31250852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com