12. 设计如下界面,在界面上方有一个标签“I’m a able”,中间有一个随机颜色的圆形,下方有两个按钮,点击点击“change lable”后标签改变为“ouch!”。点击“change circle”后圆改变颜色。用Java
时间: 2024-03-03 18:51:28 浏览: 44
下面是一个简单的Java程序实现该界面功能的代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class MyGUI extends JFrame implements ActionListener {
private JLabel label;
private JButton changeLabelButton;
private JButton changeCircleButton;
private JPanel panel;
public MyGUI() {
setTitle("MyGUI");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
label = new JLabel("I'm a able");
label.setHorizontalAlignment(JLabel.CENTER);
panel.add(label, BorderLayout.NORTH);
CirclePanel circlePanel = new CirclePanel();
panel.add(circlePanel, BorderLayout.CENTER);
changeLabelButton = new JButton("Change Label");
changeLabelButton.addActionListener(this);
panel.add(changeLabelButton, BorderLayout.WEST);
changeCircleButton = new JButton("Change Circle");
changeCircleButton.addActionListener(this);
panel.add(changeCircleButton, BorderLayout.EAST);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == changeLabelButton) {
label.setText("Ouch!");
} else if (e.getSource() == changeCircleButton) {
panel.remove(1);
panel.add(new CirclePanel(), BorderLayout.CENTER);
panel.revalidate();
panel.repaint();
}
}
private class CirclePanel extends JPanel {
private Color color;
public CirclePanel() {
Random rand = new Random();
color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillOval(100, 100, 200, 200);
}
}
public static void main(String[] args) {
MyGUI gui = new MyGUI();
}
}
```
在这个程序中,使用了JFrame、JLabel、JButton和JPanel等Swing组件实现了界面的设计。其中,CirclePanel类继承自JPanel,实现了绘制一个随机颜色的圆形的功能。在按钮的监听器中,实现了改变标签和改变圆形颜色的功能。运行程序后,即可看到界面的效果。
阅读全文