我的程序中需要三个按钮(最后一个是退出按钮,它已经有效)另外两个按钮需要更改蓝色和红色之间JPanel
背景的颜色。
我需要知道AtionListeners
中的内容,以便在按下按钮时更改背景颜色。
这是迄今为止的课程:
package myPackageNameGoesHere;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class EventPanel extends JPanel {
private static final long serialVersionUID = 123796234;
private JButton blueButton;
private JButton redButton;
private JButton exitButton;
public EventPanel() {
this.setPreferredSize(new Dimension(200, 300));
this.blueButton = new JButton("Blue");
this.add(this.blueButton);
this.redButton = new JButton("Red");
this.add(this.redButton);
this.exitButton = new JButton("Exit");
this.exitButton.addActionListener(new ExitListener());
this.add(this.exitButton);
}
private class BlueListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent blue) {
// What goes here?????
}
}
private class RedListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent red) {
// What goes here????
}
}
private class ExitListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent exit) {
System.exit(0);
}
}
}
答案 0 :(得分:2)
您不必为每个按钮声明一个侦听器类,您可以使用相同的一个并添加if语句来确定该动作来自哪个按钮。
if (e.getSource() == blueButton) {// e is the ActionEvent
blueButton.getParent().setBackground(Color.BLUE);
} else if(e.getSource() == redButton) {
redButton.getParent().setBackground(Color.RED);
}
答案 1 :(得分:2)
您可以设置按钮的父组件的背景颜色
Component component = (Component) event.getSource();
component.getParent().setBackground(Color.BLUE);