创建一个面板;在JPanel面板上放置三个JRadioButton按钮,代表“红”、“黄”、“蓝”;将按钮添加到panel面板和ButtonGroup按钮组中并添加监听器,选择三个JRadioButton按钮可以改变面板的颜色。
时间: 2024-03-27 16:38:17 浏览: 47
好的,下面是Java代码实现:
```java
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.JPanel;
import javax.swing.JRadioButton;
public class ColorPanel extends JFrame implements ActionListener {
private JPanel panel;
private JRadioButton redButton, yellowButton, blueButton;
private ButtonGroup buttonGroup;
public ColorPanel() {
setTitle("Color Panel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
panel = new JPanel();
redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
blueButton = new JRadioButton("Blue");
buttonGroup = new ButtonGroup();
buttonGroup.add(redButton);
buttonGroup.add(yellowButton);
buttonGroup.add(blueButton);
redButton.addActionListener(this);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
panel.add(redButton);
panel.add(yellowButton);
panel.add(blueButton);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (redButton.isSelected()) {
panel.setBackground(Color.RED);
} else if (yellowButton.isSelected()) {
panel.setBackground(Color.YELLOW);
} else if (blueButton.isSelected()) {
panel.setBackground(Color.BLUE);
}
}
public static void main(String[] args) {
new ColorPanel();
}
}
```
运行程序,你将会看到一个有三个单选按钮的面板,当你选择单选按钮时,面板的背景颜色会随之改变。
阅读全文