在GUI上绘图

在GUI上添加东西的3种方法:
1.在frame上放置widget:

frame.getContentPane().add(widget);

2.在widget上绘制2D图形;
3.在widget上绘制JPEG图。

2与3均使用graphics对象来绘制图;

创建绘图组件

方法2:显示绘制的2D图形

创建出自己的widget,并将其放到frame上

创建JPanel的子类,并且重写paintComponent()这个方法

public class MyDrawPanel extends JPanel {
	public void paintComponent(Graphics g) {

		g.setColor(Color.orange);

		g.fillRect(20, 50, 100, 100);
	}
}
//设置颜色:
g.setColor(Color.orange);//设为orange的颜色
//设置随机颜色:
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
		
Color randomColor = new Color(red,green,blue);
g.setColor(randomColor);


//画矩形:
g.fillRect(20, 50, 100, 100);
//参数分别起始X坐标,起始Y坐标,宽度,高度。
//画椭圆:
g.fillOval(20,50,100,100)
//参数分别起始X坐标,起始Y坐标,X轴长度,Y轴长度。

测试代码:

public static void main(String[] args) {
		JFrame frame = new JFrame();

		MyDrawPanel myDraw = new MyDrawPanel();

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		frame.getContentPane().add(myDraw);

		frame.setSize(300, 300);

		frame.setVisible(true);
	}

效果:生成orange的矩形框
在这里插入图片描述
在这里插入图片描述
随机生成颜色:理论上来说每次都不一样
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

方法3:显示JPEG图像

public void paintComponent(Graphics g) {

		Image image = new ImageIcon("JPEG图像名").getImage();

		g.drawImage(image, 3, 4, this);

	}

Graphics与Graphics2D

public void paintComponent(Graphics g) 

参数g是个Graphics对象,但是实际所引用的时Graphics的子类Graphics2D(多态)。

Graphics2D在Graphics的基础上实现其他的功能,但是以Graphics对象声明的g无法使用,因此需要对g进行转换:

Graphics2D g2d = (Graphics2D) g;

在获得事件时,绘制图形

public class ChangeColor {
	JFrame frame;
	JButton button;
	
	public void go() {
		frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		button = new JButton("Button");
		button.addActionListener((ActionListener) new Button());

		MyDrawPanel myDraw = new MyDrawPanel();
		
		frame.getContentPane().add(BorderLayout.SOUTH, button);
		frame.getContentPane().add(BorderLayout.CENTER, myDraw);
		
		frame.setSize(300, 300);
		frame.setVisible(true);
	}
	
	class Button implements ActionListener {

		public void actionPerformed(ActionEvent event) {
			frame.repaint();
		}
	}
	
	public static void main(String[] args) {
		ChangeColor tb = new ChangeColor();
		tb.go();
	}
}
public class MyDrawPanel extends JPanel {
	public void paintComponent(Graphics g) {

		int red = (int) (Math.random() * 255);
		int green = (int) (Math.random() * 255);
		int blue = (int) (Math.random() * 255);
		
		Color randomColor = new Color(red,green,blue);
		
		g.setColor(randomColor);

		g.fillRect(20, 50, 100, 100);
	}
}

效果:
在这里插入图片描述
点击按钮后:
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值