11. 设计如下界面,在界面上方有一个标签“I’m a able”,中间有一个随机颜色的圆形,下方有两个按钮,点击点击“change lable”后标签改变为“ouch!”。点击“change circle”后圆改变颜色。用Java
时间: 2024-03-06 21:50:48 浏览: 43
java程序,界面上圆形随按钮不同而变色
5星 · 资源好评率100%
可以使用Java的Swing库来设计这个界面,以下是基本的代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyApp extends JFrame {
private JLabel label;
private JPanel circlePanel;
private JButton changeLabelButton;
private JButton changeCircleButton;
public MyApp() {
setTitle("My App");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
label = new JLabel("I'm able");
label.setFont(new Font("Arial", Font.PLAIN, 20));
label.setHorizontalAlignment(JLabel.CENTER);
add(label, BorderLayout.NORTH);
circlePanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(getRandomColor());
g.fillOval(10, 10, 80, 80);
}
};
circlePanel.setPreferredSize(new Dimension(100, 100));
add(circlePanel, BorderLayout.CENTER);
changeLabelButton = new JButton("Change Label");
changeLabelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Ouch!");
}
});
add(changeLabelButton, BorderLayout.WEST);
changeCircleButton = new JButton("Change Circle");
changeCircleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
circlePanel.repaint();
}
});
add(changeCircleButton, BorderLayout.EAST);
}
private Color getRandomColor() {
int r = (int) (Math.random() * 256);
int g = (int) (Math.random() * 256);
int b = (int) (Math.random() * 256);
return new Color(r, g, b);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyApp().setVisible(true);
}
});
}
}
```
这段代码创建了一个继承自JFrame的MyApp类,其中包含标签、圆形和两个按钮。在圆形面板的paintComponent()方法中,使用Graphics类的fillOval()方法来绘制圆形。在按钮的ActionListener中,可以动态修改标签和圆形的属性。使用getRandomColor()方法来生成随机颜色。在main()方法中使用SwingUtilities.invokeLater()方法来启动应用程序。
阅读全文