编写一个java应用程序,实现如下图所示的图形界面,要求单击按钮将窗口的背景颜色设置为相应的颜色。设置颜色可以调用容器的setBackground(Color c)方法,参数Color可以使用java awt.Color类的常量,如Color.RED等。
时间: 2024-03-01 17:53:14 浏览: 22
好的,我可以帮你解答这个问题。以下是实现该图形界面的Java代码:
```java
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BackgroundColorChanger extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton redButton;
private JButton greenButton;
private JButton blueButton;
private JPanel panel;
public BackgroundColorChanger() {
setSize(300, 300);
setTitle("Background Color Changer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
panel = new JPanel();
panel.setBackground(Color.WHITE);
add(panel);
redButton = new JButton("Red");
redButton.addActionListener(this);
add(redButton);
greenButton = new JButton("Green");
greenButton.addActionListener(this);
add(greenButton);
blueButton = new JButton("Blue");
blueButton.addActionListener(this);
add(blueButton);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == redButton) {
panel.setBackground(Color.RED);
} else if (e.getSource() == greenButton) {
panel.setBackground(Color.GREEN);
} else if (e.getSource() == blueButton) {
panel.setBackground(Color.BLUE);
}
}
public static void main(String[] args) {
BackgroundColorChanger backgroundColorChanger = new BackgroundColorChanger();
backgroundColorChanger.setVisible(true);
}
}
```
这个程序创建了一个名为“Background Color Changer”的窗口,包含一个白色面板和三个按钮(红色、绿色和蓝色),单击每个按钮将窗口的背景颜色更改为相应的颜色。当单击任何一个按钮时,`actionPerformed()`方法将被调用,该方法将检查事件源并相应地更改面板的背景颜色。