画一个渐变色球,用内部类实现监听两个button
来源:互联网 发布:手机淘宝首页红包 编辑:程序博客网 时间:2024/03/29 04:04
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class Circle {JFrame jframe;JLabel jlabel;public void draw_circle(){jframe = new JFrame();//创建framejlabel = 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}}