所以我最近做了一些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);
}
}
画布.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();
}
}
}