java当点击“东”“南”“西”“北”四个按钮时,改变中心按钮的背景颜色
时间: 2023-10-30 07:06:14 浏览: 38
以下是一个简单的Java代码示例,用于实现用四个按钮改变中心按钮的背景颜色:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo extends JFrame implements ActionListener {
JButton northBtn, southBtn, eastBtn, westBtn, centerBtn;
public ButtonDemo() {
// 设置窗口标题
setTitle("Button Demo");
// 设置窗口布局
setLayout(new BorderLayout());
// 创建四个按钮
northBtn = new JButton("North");
southBtn = new JButton("South");
eastBtn = new JButton("East");
westBtn = new JButton("West");
// 创建中心按钮
centerBtn = new JButton("Center");
// 设置中心按钮的初始背景颜色
centerBtn.setBackground(Color.WHITE);
// 添加按钮到窗口布局
add(northBtn, BorderLayout.NORTH);
add(southBtn, BorderLayout.SOUTH);
add(eastBtn, BorderLayout.EAST);
add(westBtn, BorderLayout.WEST);
add(centerBtn, BorderLayout.CENTER);
// 给四个按钮添加事件监听器
northBtn.addActionListener(this);
southBtn.addActionListener(this);
eastBtn.addActionListener(this);
westBtn.addActionListener(this);
// 设置窗口大小并可见
setSize(new Dimension(300, 300));
setVisible(true);
}
// 事件处理方法,根据点击的按钮改变中心按钮的背景颜色
public void actionPerformed(ActionEvent e) {
if (e.getSource() == northBtn) {
centerBtn.setBackground(Color.RED);
} else if (e.getSource() == southBtn) {
centerBtn.setBackground(Color.BLUE);
} else if (e.getSource() == eastBtn) {
centerBtn.setBackground(Color.GREEN);
} else if (e.getSource() == westBtn) {
centerBtn.setBackground(Color.YELLOW);
}
}
public static void main(String[] args) {
new ButtonDemo();
}
}
```
运行代码后,会出现一个带有五个按钮的窗口。当点击“North”、“South”、“East”或“West”按钮时,中心按钮的背景颜色会分别变为红色、蓝色、绿色或黄色。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)