用java编写一个窗体应用程序,在窗体中加入一个按钮,点击按钮时,则按钮的颜色在红(red),橙(orange),黄(yellow),绿(green),蓝(blue),几种颜色中随机变化的完整代码
时间: 2023-10-02 15:12:09 浏览: 34
以下是一个使用Java Swing编写的窗体应用程序,其中包含一个按钮,点击按钮时,按钮的颜色会随机变化。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class ColorButton extends JFrame implements ActionListener {
private JButton button;
public ColorButton() {
super("Color Button");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建按钮
button = new JButton("Click me!");
button.addActionListener(this);
// 将按钮添加到窗体中心
getContentPane().add(button, BorderLayout.CENTER);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
Random random = new Random();
int colorIndex = random.nextInt(6);
Color[] colors = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE, Color.PINK};
button.setBackground(colors[colorIndex]);
}
public static void main(String[] args) {
new ColorButton();
}
}
```
在 `actionPerformed` 方法中,我们使用 `java.util.Random` 类生成一个随机数,然后根据随机数选择一种颜色,将按钮的背景颜色设置为所选择的颜色。在这个例子中,我们使用了 6 种颜色:红(red)、橙(orange)、黄(yellow)、绿(green)、蓝(blue)、粉(pink)。