Java编写Example04类,创建一个面板;在JPanel面板上放置三个JRadioButton按钮,代表“红”、“黄”、“蓝”;将按钮添加到panel面板和ButtonGroup按钮组中并添加监听器,选择三个JRadioButton按钮可以改变面板的颜色。
时间: 2024-03-27 08:38:19 浏览: 19
好的,这是一个Java编写的Example04类,实现了在JPanel面板上放置三个JRadioButton按钮,可以改变面板的颜色:
```java
import java.awt.Color;
import java.awt.FlowLayout;
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 Example04 extends JFrame implements ActionListener {
private JPanel panel;
private JRadioButton redButton, yellowButton, blueButton;
private ButtonGroup colorGroup;
public Example04() {
setTitle("Color Panel");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(new FlowLayout());
redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
blueButton = new JRadioButton("Blue");
colorGroup = new ButtonGroup();
colorGroup.add(redButton);
colorGroup.add(yellowButton);
colorGroup.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 (e.getSource() == redButton) {
panel.setBackground(Color.RED);
} else if (e.getSource() == yellowButton) {
panel.setBackground(Color.YELLOW);
} else if (e.getSource() == blueButton) {
panel.setBackground(Color.BLUE);
}
}
public static void main(String[] args) {
new Example04();
}
}
```
这个程序创建了一个JFrame窗口,其中放置了一个JPanel面板和三个JRadioButton按钮。将三个按钮添加到ButtonGroup按钮组中,并添加监听器,当选择不同的按钮时,可以改变面板的背景颜色。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)