【发布时间】: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