您的位置:首页 > 其它

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

2012-04-10 11:45 344 查看
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
}
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐