用Java编写实现程序,在窗口North上布置三个按钮,并完成按钮点击事件

点击三个按钮时分别输出填充颜色的三角形,矩形和椭圆。
2025-04-15 02:40:24
推荐回答(1个)
回答1:

代码如下:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Polygon;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class App extends JFrame {

public App() {

this.setSize(300, 300);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel topBar = new JPanel();
topBar.setLayout(new FlowLayout());
this.add(topBar, BorderLayout.NORTH);

JPanel canvas = new JPanel();
this.add(canvas, BorderLayout.CENTER);

JButton btnTriangle = new JButton("三角形");
btnTriangle.addActionListener(e -> {

Graphics g = canvas.getGraphics();

g.setColor(Color.RED);

Polygon polygon = new Polygon();
polygon.addPoint(10, 10);
polygon.addPoint(10, 50);
polygon.addPoint(100, 50);

g.fillPolygon(polygon);
});
topBar.add(btnTriangle);

JButton btnRectangle = new JButton("矩形");
btnRectangle.addActionListener(e -> {

Graphics g = canvas.getGraphics();

g.setColor(Color.RED);

g.fillRect(150, 10, 100, 50);
});
topBar.add(btnRectangle);

JButton btnCircle = new JButton("椭圆");
btnCircle.addActionListener(e -> {

Graphics g = canvas.getGraphics();

g.setColor(Color.GREEN);

g.fillOval(10, 100, 250, 90);
});
topBar.add(btnCircle);
}

public static void main(String[] args) {
new App().setVisible(true);
}
}

运行结果: