我的代码有什么问题?当我想通过radioButton改变颜色时,它不会改变颜色。我所说的if语句对我来说很有意义,但是他们没有注册背景来改变颜色到setbackground方法。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.event.ChangeListener;
public class GetTheColors extends JFrame
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGTH = 400;
JLabel label;
JPanel colorPanel;
JFrame frame;
JRadioButton redButton;
JRadioButton blueButton;
JRadioButton greenButton;
ActionListener listen;
public GetTheColors()
{
colorPanel = new JPanel();
add(colorPanel, BorderLayout.CENTER);
RadioButtons();
setColor();
setSize(FRAME_WIDTH,FRAME_HEIGTH);
}
class ChoiceListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
setColor();
}
}
public JPanel RadioButtons()
{
redButton = new JRadioButton("red");
redButton.addActionListener(listen);
redButton.setSelected(true);
greenButton = new JRadioButton("green");
greenButton.addActionListener(listen);
blueButton = new JRadioButton("blue");
blueButton.addActionListener(listen);
ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(greenButton);
group.add(blueButton);
JPanel buttonPanel = new JPanel();
buttonPanel.add(redButton);
buttonPanel.add(greenButton);
buttonPanel.add(blueButton);
add(buttonPanel, BorderLayout.NORTH);
return buttonPanel;
}
/**
*
*/
public void setColor()
{
if (redButton.isSelected())
{
colorPanel.setBackground(Color.red);
colorPanel.repaint();
}
else if (blueButton.isSelected())
{
colorPanel.setBackground(Color.blue);
colorPanel.repaint();
}
else if (greenButton.isSelected())
{
colorPanel.setBackground(Color.green);
colorPanel.repaint();
}
}
}
答案 0 :(得分:0)
您需要初始化ActionListener:
ActionListener listen = new ChoiceListener();