Java程序设计2023-第五次上机测试

8-1使用按钮选择绘制不同图形

编写一个程序,实现如下的界面,当点击不同按钮时绘制相应的图形。点击“椭圆”,绘制一个椭圆形;点击“矩形”,绘制一个矩形;点击“直线”,绘制一条直线。实现图形绘制即可,图形位置和大小自定。
参考代码

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class b{
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				ChangeGraphFrame frame = new ChangeGraphFrame();
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.setVisible(true);
				}
			});
		}
}
class ChangeGraphFrame extends JFrame {
	private GraphComponent graphComponent;
	public ChangeGraphFrame() {
	setSize(250, 200);
	setTitle("绘制图形");
	graphComponent = new GraphComponent();
	add(graphComponent, BorderLayout.CENTER);
	
	JButton elipseButton = new JButton("椭圆");
	elipseButton.addActionListener(new ChangeGraphAction(1));
	JButton rectButton = new JButton("矩形");
	rectButton.addActionListener(new ChangeGraphAction(2));
	JButton lineButton = new JButton("直线");
	lineButton.addActionListener(new ChangeGraphAction(3));
	JPanel buttonPanel = new JPanel();
	buttonPanel.add(elipseButton);
	buttonPanel.add(rectButton);
	buttonPanel.add(lineButton);
	add(buttonPanel, BorderLayout.SOUTH);
}
private class ChangeGraphAction implements ActionListener {
	private int choice;
	public ChangeGraphAction(int choice) {
		this.choice = choice;
	}
	public void actionPerformed(ActionEvent event) {
		graphComponent.setGraphChoice(choice);
		repaint();
	}
	}
}

class GraphComponent extends JComponent {
	private int graphChoice = 0;
	public int getGraphChoice() {
		return graphChoice;
	}
	public void setGraphChoice(int graphChoice) {
		this.graphChoice = graphChoice;
	}
	public void paintComponent(Graphics g) {
		Graphics2D g2 = (Graphics2D) g;
		Ellipse2D elipse = new Ellipse2D.Double(70, 10, 100, 100);
		Rectangle2D rect = new Rectangle2D.Double(70, 10, 100, 100);
		Line2D line = new Line2D.Double(10, 10, 200, 100);
		switch (graphChoice) {
			case 1:
				g2.draw(elipse);
				break;
			case 2:
				g2.draw(rect);
				break;
			case 3:
				g2.draw(line);
				break;
			}
		}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值