Java:程序不保存旧图形

时间:2015-10-06 15:53:08

标签: java swing jpanel paintcomponent

所以,我已经做了几个月的Java了,现在我正在学习图形。所以,我正试图制作一种油漆类的东西,我可以用鼠标画画。没什么好看的,只是让我开始的东西。每当我拖动鼠标时,程序就会画一个小点。它有点作用,除了它不能保存我的旧点。它只是创造了一个新的!如果有人可以帮我解决这个问题,那就太好了:

主要课程:

import javax.swing.JFrame;

public class Test{
    public static void main(String args[]){

        Ploofer ploof = new Ploofer();
        PumpkinPie f = new PumpkinPie(ploof);

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(1000,1000);
        f.setResizable(false);
        ploof.setSize(1000,1000);
        f.add(ploof);
        f.setVisible(true);
    }
}

“Ploofer”课程:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

public class Ploofer extends JPanel{

    PumpkinPie pObj = new PumpkinPie(this);

    @Override
    public void paintComponent(Graphics g){

        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

        this.setBackground(Color.WHITE);

        g2d.setColor(new Color(190, 50, 0));

        if(pObj.draw==true){
            g2d.fillRect(pObj.x, pObj.y, 2, 2);
            pObj.draw = false;
        }
    }

    @Override
    public void update(Graphics g){
        paint(g);
    }

    //I tried to override update, but it didn't really help

}

“PumpkinPie”课程:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

public class Ploofer extends JPanel{

    PumpkinPie pObj = new PumpkinPie(this);

    @Override
    public void paintComponent(Graphics g){

        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

        this.setBackground(Color.WHITE);

        g2d.setColor(new Color(190, 50, 0));
    /*  g2d.fillRect(475, 475, 50, 50);
        g2d.drawString("^Red^", 484, 540); */

        if(pObj.draw==true){
            g2d.fillRect(pObj.x, pObj.y, 2, 2);
            pObj.draw = false;
        }
    }

    @Override
    public void update(Graphics g){
        paint(g);
    }

    //I tried to override update, but it didn't really help

}

1 个答案:

答案 0 :(得分:2)

  除了事实上它没有保存我的旧点之外,它有点起作用。它只会创建一个新的!

查看Custom Painting Approaches了解自定义绘画的两种常用方法:

  1. 添加绘制到ArrayList的对象并遍历列表以绘制所有对象
  2. 绘制到BufferedImage并重新绘制BufferedImage
  3. 在你的情况下,我建议采用方法2.

      

    //我试图覆盖更新,但它并没有真正帮助

    不要覆盖update()。没有理由这样做。这是Swing中不需要的旧AWT方法。