gpt4 book ai didi

Java:程序不保存旧图形

转载 作者:行者123 更新时间:2023-11-30 03:14:24 24 4
gpt4 key购买 nike

所以,我已经学习 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

}

“南瓜派”类:

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

}

最佳答案

It sort of works, except for the fact that it doesn't save my old dots. It just creates a new one!

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

  1. 将要绘制的对象添加到 ArrayList 并迭代列表以绘制所有对象
  2. 绘制 BufferedImage 并重新绘制 BufferedImage

对于您的情况,我建议采用方法 2。

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

不要重写 update()。没有理由这样做。这是一种旧的 AWT 方法,在 Swing 中不需要。

关于Java:程序不保存旧图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32974333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com