我试图在内部类 JPanel 中覆盖方法paintComponent 并绘制一些图片。但是,如果我在构造函数中加载图像,则不会调用方法 paintComponent。如果在主类中加载图像,一切都很好。它是什么?这是代码,这不起作用
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
JFrame window;
//Image image=new ImageIcon("D://domik.png").getImage();
class JPanelExt extends JPanel {
Image image;
public JPanelExt (){
image=new ImageIcon("D://domik.png").getImage();
System.out.println("constructor");
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("paint");
g.drawImage(image, 0, 0, this);
g.drawRect(0, 400, 100, 100);
}
}
public Main(){
window=new JFrame("Flowers");
window.setSize(430, 480);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanelExt flower1 =new JPanelExt();
flower1.setBounds(100, 100, 200, 200);
flower1.setToolTipText("House");
window.setLayout(null);
window.add(flower1);
}
public static void main(String[] args) {
Main main=new Main();
}
}
而 sysout 只写“构造函数”
但是如果我以这种方式更改代码
public class Main {
JFrame window;
Image image=new ImageIcon("D://domik.png").getImage();
class JPanelExt extends JPanel {
//Image image;
public JPanelExt (){
//image=new ImageIcon("D://domik.png").getImage();
System.out.println("constructor");
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("paint");
g.drawImage(image, 0, 0, this);
g.drawRect(0, 400, 100, 100);
}
并且 sysout 写“constructor”、“paint”
我无法理解这个))