所以我最近做了一些java工作,并且遇到了一些问题。我一直在尝试 2D 绘图并向项目添加图像。
问题是当窗口调整大小时,它会重新绘制并复制图像。我做了一些解决方法,但它并不理想......那么为什么图像会重复?
之前: http://i.imgur.com/PmHRZBQ.png
(窗口大小已调整)
之后: http://i.imgur.com/bhsvVZz.png
代码
main.java
import javax.swing.JFrame;
public class main
{
public static void main(String [] args) throws InterruptedException
{
JFrame f = new JFrame("Title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Canvas testing = new Canvas();
f.add(testing);
f.setSize(800, 600);
f.setVisible(true);
}
}
canvas.java
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Canvas extends JPanel
{
public void paintComponent (Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.setColor(Color.BLACK);
g.fillRect(25, 25, 100, 30);
g.setColor(new Color(190,81,215));
g.fillRect(25, 68, 10, 10);
g.setColor(Color.RED);
g.drawString("Matt is da best", 100, 10);
try
{
BufferedImage image = ImageIO.read(new File("C:/face.png"));
JLabel picLabel = new JLabel(new ImageIcon(image));
System.out.println("Added pic");
add(picLabel);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
最佳答案
- 不要在
paintComponent(Graphics)
方法中加载图像!它可以被声明为类属性并加载到构造函数中。 - 也不要在
paintComponent
方法中添加组件!它将触发重绘。
这应该工作得更可靠..
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class main
{
public static void main(String [] args) throws InterruptedException
{
JFrame f = new JFrame("Title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Canvas testing = new Canvas();
f.add(testing);
f.setSize(800, 600);
f.setVisible(true);
}
}
class Canvas extends JPanel
{
BufferedImage image;
Canvas() {
image = new BufferedImage(200,200,BufferedImage.TYPE_INT_RGB);
JLabel picLabel = new JLabel(new ImageIcon(image));
System.out.println("Added pic");
add(picLabel);
}
public void paintComponent (Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.setColor(Color.BLACK);
g.fillRect(25, 25, 100, 30);
g.setColor(new Color(190,81,215));
g.fillRect(25, 68, 10, 10);
g.setColor(Color.RED);
g.drawString("Matt is da best", 100, 10);
}
}
其他提示
- 让
Canvas
返回首选尺寸并pack()
框架,而不是为其设置尺寸。 - 在 EDT 上启动并更新 Swing GUI。
- 不要为您的自定义类指定与 J2SE 类相同的名称。这可能会让人感到困惑。也许称其为
JCanvas
。
关于Java重绘重复图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16536670/