我正在尝试编写一个程序,其中有3个不同的按钮,当您单击按钮时,它会更改框架中面板的背景。我设置了面板,一切都在正确的位置,但是我需要在一个类中为我的按钮设置所有的动作。我试过这样做,但所有按钮都改变了颜色,而不是背景。这是我到目前为止的代码。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Kelle Schmitt
*/
public class BackgroundColorChooserFrame extends JFrame
{
private static final int WIDTH = 300;
private static final int HEIGHT = 300;
private JLabel titleLbl;
private JButton redBtn;
private JButton greenBtn;
private JButton blueBtn;
private JButton quitBtn;
public BackgroundColorChooserFrame()
{
createButton();
createLabel();
createPanel();
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ColorListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
redBtn.setBackground(Color.red);
greenBtn.setBackground(Color.green);
blueBtn.setBackground(Color.blue);
}
}
public void createButton()
{
redBtn = new JButton("Red");
greenBtn = new JButton("Green");
blueBtn = new JButton("Blue");
ActionListener colorlistener = new ColorListener();
redBtn.addActionListener(colorlistener);
greenBtn.addActionListener(colorlistener);
blueBtn.addActionListener(colorlistener);
}
public void createLabel()
{
titleLbl = new JLabel("Background Color Chooser");
}
//create and add panels
public void createPanel()
{
JPanel mainPnl, titlePnl, colorPnl, controlPnl;
mainPnl = new JPanel();
mainPnl.setLayout(new BorderLayout());
titlePnl = new JPanel();
colorPnl = new JPanel();
controlPnl = new JPanel();
mainPnl.add(titlePnl, BorderLayout.NORTH);
titlePnl.add(titleLbl);
mainPnl.add(colorPnl, BorderLayout.CENTER);
mainPnl.add(controlPnl, BorderLayout.SOUTH);
controlPnl.add(redBtn);
controlPnl.add(greenBtn);
controlPnl.add(blueBtn);
//add the mainPnl to the parent frame
add(mainPnl);
}
}
请帮忙!谢谢!
答案 0 :(得分:3)
可能是这样的:
public void actionPerformed(ActionEvent evt)
{
JButton button = (JButton)evt.getSource();
Component parent = button.getParent();
if (button == redBtn)
parent.setBackground( Color.RED );
else if (...)
}
虽然更好的解决方案是为每个按钮创建一个单独的ActionListener,因此不要使用嵌套的if / else逻辑:
public class ColorListener implements ActionListener
{
private Color background;
public ButtonListener(Color background)
{
this.background = background;
}
@Override
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)evt.getSource();
Component parent = button.getParent();
parent.setBackground( background );
}
}
然后您可以创建无限数量的按钮和颜色:
redButton.addActionListener( new ColorListener(Color.RED) );
关键是使用getSource()
方法,因此您可以编写通用代码。