画一个渐变色球,用内部类实现监听两个button

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Circle  {
JFrame jframe;
JLabel jlabel;
	public void draw_circle(){
	jframe = new JFrame();//创建frame
	jlabel = new JLabel("我想看你的笑颜。");//创建标签并初始显示文字“我想看你的笑颜。”
	JButton jbutton_label = new JButton("我想");//创建按钮,按钮显示文字 “我想”
	JButton jbutton = new JButton("点击");//创建另一个按钮显示文字“点击”
	PaintCircle paint_circle = new PaintCircle();//创造JPanel的子类,并覆盖父类方法paintComponent(),实现画圆的方法
	jframe.getContentPane().add(BorderLayout.WEST,jlabel);//把标签加入到frame中并放置到左边
	jframe.getContentPane().add(BorderLayout.EAST,jbutton_label);//把控制标签的按钮加入frame并放置到右边
	jframe.getContentPane().add(BorderLayout.CENTER,paint_circle);//把填充的画布居中放置
	jframe.getContentPane().add(BorderLayout.SOUTH,jbutton);//把控制重绘方法调用的按钮放置在最下方
	jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//windows关闭时结束程序
	jbutton.addActionListener(new PaintListener());//向监听列表中注册,向监听的注册方法传入对象
	jbutton_label.addActionListener(new LabelListener());//同上
	jframe.setSize(400,400);//指定frame大小
	jframe.setVisible(true);//设定frame是否可见,true可见
}   /*创建内部类实现接口ActionListener中的actionPerformed()方法进行对事件的处理,内部类可以自由读取Circle实例*/  
	class PaintListener implements ActionListener{
	public void actionPerformed(ActionEvent event){
		jframe.repaint();
	}
	}
	/*创建内部类实现接口ActionListener中的actionPerformed()方法进行对事件的处理,内部类可以自由读取Circle实例*/
	class LabelListener implements ActionListener{
		public void actionPerformed(ActionEvent event){
			jlabel.setText("我想占有你 。     ");
		}
	}
	public static void main(String [] args){
		Circle start = new Circle();
		start.draw_circle();
	}
}
//创造JPanel的子类,并覆盖父类方法paintComponent(),实现画圆的方法
class PaintCircle extends JPanel{
	public void paintComponent(Graphics g){
		Graphics2D g2d = (Graphics2D)g;//使用Graphics2D的方法对g进行强制类型转换
		g.fillRect(0,0, this.getWidth(),this.getHeight());//从0,0坐标使用默认颜色填充一个矩形
		int red = (int)(Math.random()*255);
		int green = (int)(Math.random()*255);
		int yellow = (int)(Math.random()*255);
		Color startColor = new Color(red,green,yellow);//随机产生一种颜色,Color没有无参数的构造函数
		int red1 = (int)(Math.random()*255);
		int green1 = (int)(Math.random()*255);
		int yellow1 = (int)(Math.random()*255);
		Color endColor = new Color(red1,green1,yellow1);//随机产生一种颜色,Color没有无参数的构造函数
		GradientPaint set = new GradientPaint(70,70,startColor,150,150,endColor);//产生一个色彩从70,70坐标到坐标150,150的另一个色彩的变化
		g2d.setPaint(set);
		g2d.fillOval(70,70,150,150);//使用set对象的颜色填充70,70坐标,宽为150,高为150
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值