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

点击三个按钮时分别输出填充颜色的三角形,矩形和椭圆。

代码如下:

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);
}
}

运行结果:

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网