软件编程
位置:首页>> 软件编程>> java编程>> java GUI编程之paint绘制操作示例

java GUI编程之paint绘制操作示例

作者:qq_42412646  发布时间:2023-11-24 17:58:39 

标签:java,GUI,paint

本文实例讲述了java GUI编程之paint绘制操作。分享给大家供大家参考,具体如下:


import java.awt.*;
public class Testpint {
   public static void main(String[] args) {
//        new TFPaint().lunchPaint();
       new TFPaint();
   }
}
class TFPaint extends Frame{
   /*
   public void lunchPaint() {
       this.setBounds(200, 200, 640, 640);
       this.setBackground(Color.BLUE);
       this.setVisible(true);
   }
   */
   TFPaint(){
       this.setBounds(200, 200, 200, 200);
       this.setBackground(Color.BLUE);
       this.setVisible(true);
   }
   public void paint(Graphics g) {
       Color c = g.getColor();
       g.setColor(Color.BLACK);
       g.fillRect(60, 60, 30, 30);
       g.setColor(Color.CYAN);
       g.fillOval(80, 80, 40, 40);
       g.setColor(c);
   }
}

paint方法是container类的一个方法,其能够实现绘图的功能,其是本身自带的方法,我们相当于重写了这个方法,在调用时我们用到了参数(Graphics g),一个画笔,用g来实现绘画,Frames是container的一个子类,所以我们在Frame里重写了Paint方法。

注;Color c = g.getColor(),和g.setColor(c),相当于把画笔用完后,重新置为原来的颜色。

Paint 的一个实例,外加MouseMonitor的介绍。


import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TestPaint2 {
   public static void main(String[] args) {
       new TFpaint("Draw");
   }
}
class TFpaint extends Frame{
   ArrayList pointList = null;
   TFpaint(String s){
       super(s);
       pointList = new ArrayList();
       this.setLayout(null);
       this.setBounds(200, 200, 400, 400);
       this.setBackground(Color.blue);
       this.setVisible(true);
       this.addMouseListener(new MyMouseMonitor());
   }
   public void paint(Graphics g ) {
       Iterator i = pointList.iterator();
       while(i.hasNext()) {
           Point p = (Point)i.next();
           g.setColor(Color.BLACK);
           g.fillOval(p.x, p.y, 10, 10);
       }
   }
   public void addPoint(Point p) {
       pointList.add(p);
   }
}
class MyMouseMonitor extends MouseAdapter{
   public void mousePressed(MouseEvent e) {
       TFpaint f = (TFpaint) e.getSource();
       f.addPoint(new Point(e.getX(),e.getY()));
       f.repaint();
   }
}

基本要求:实现在一个界面上鼠标每点击一下,就会生成一个点,

基本思路:要有一个Frame,用来显示界面,由于需要在这个界面上产生点,所以我们有鼠标点击产生点,即有对鼠标的监听,而我们要在监听后产生点,所以我们有Paint方法用来绘图,而他绘制的图就是产生一个点。

其中较为麻烦的就是,必须在指定位置(即鼠标点击的位置产生一个点)如何来找到这个位置,在此时我们在MouseMonitor中利用e.getSource获得信息,其中e是点击这个事件发生时,我们把他包装成一个类,传输给Monitor(其内部含有事件处理方法)

注:在Frame中我们要显示多个点,所以我们建立了一个ArrayList,用来存储点类型数据,在Frame中存储的过程就相当于画在了上面,

getSource是重新定义到一个新的来源,如上文,我们把e的getSource赋值给了f(一个Frame)相当于对frame进行添加,即Frame拿到了属于Monitor的画笔,我们通过e.getx,e和e.gety,进行定位,x,y,确定的就是鼠标点击的点,addpoint,相当于点一下在Frame上添加一个点,而print就是把哪些点用圆圈表示出来,

由于点数据是用ArrayList存储的所以对应的我们进行索引的时候用了Iterator,只要在列表里有一个点就用圆圈表示出来。

repaint,是将画面重新显示出来,感觉相当于刷新界面,如果没有,在界面上虽然有点但是他不显示,只有重传界面(即界面刷新时才会出现)

希望本文所述对大家java程序设计有所帮助。

来源:https://blog.csdn.net/qq_42412646/article/details/102395554

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com