我正在尝试在使用无线电按钮时更改背景颜色。现在我有框架和按钮(红色,绿色和蓝色)显示。我设置了一种方法来在选择按钮时更改颜色,但背景不会改变。我究竟做错了什么?有什么遗漏?
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.JRadioButton;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class FontViewerFrame extends JFrame
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 400;
private JRadioButton redButton;
private JRadioButton greenButton;
private JRadioButton blueButton;
private ActionListener listener;
/**
Constructs the frame.
*/
public FontViewerFrame()
{
// This listener is shared among all components
class ChoiceListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
setColor();
}
}
listener = new ChoiceListener();
createControlPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
/**
Creates the control panel to change the color.
*/
public void createControlPanel()
{
JPanel styleGroupPanel = createRadioButtons();
// Line up component panels
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(3, 1));
controlPanel.add(styleGroupPanel);
// Add panels to content pane
add(controlPanel, BorderLayout.SOUTH);
}
/**
Creates the radio buttons to select the color.
@return the panel containing the radio buttons
*/
public JPanel createRadioButtons()
{
redButton = new JRadioButton("Red");
redButton.addActionListener(listener);
greenButton = new JRadioButton("Green");
greenButton.addActionListener(listener);
blueButton = new JRadioButton("Blue");
blueButton.addActionListener(listener);
blueButton.setSelected(true);
// Add radio buttons to button group
ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(greenButton);
group.add(blueButton);
JPanel panel = new JPanel();
panel.add(redButton);
panel.add(greenButton);
panel.add(blueButton);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Color"));
return panel;
}
public void setColor()
{
if(redButton.isSelected())
{
setBackground(Color.RED);
}
if(greenButton.isSelected())
{
setBackground(Color.GREEN);
}
if(blueButton.isSelected())
{
setBackground(Color.BLUE);
}
}
}
答案 0 :(得分:2)
getContentPane().setBackground(Color.YELLOW);
将颜色设置为您想要的颜色
答案 1 :(得分:2)
长话短说,您的controlPanel
覆盖contentPane
(因为默认布局管理器为BorderLayout
),其覆盖了覆盖框架的JRootPane
。
尝试更改controlPane
的背景颜色
您还应该记住,默认情况下,JPanel
是不透明的
答案 2 :(得分:1)
我认为您应该将动作侦听器添加到单选按钮组而不是每个单独的单选按钮