绘制组件方法不适用于 JFrame

2022-01-24 00:00:00 java swing paintcomponent paint jframe

在尝试使用 JLabel 之后,我正在尝试在屏幕上绘制图像,现在正在尝试使用 paintComponent 方法.我在没有看到任何结果并且没有调用该方法后尝试插入断点,并且什么也没有出现.我该怎么办?这是我的重要代码-

I'm trying to paint an image on the screen after trying to use JLabel's and am now trying the paintComponent method. I tried inserting breakpoints after seeing no results and the method doesn't get called, and nothing appears. What should I do? Here is my important code-

`

     public void createWindow(){        

            frame.setVisible(true);  
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.pack();
    frame.setSize(xSize, ySize);
            frame.setLocation(0, 0);
            frame.addComponentListener(this);
            //frame.add(im);             

    }

public void paintComponent(Graphics g) {super.paintComponent(g);g.drawImage(占位符, 0, 0, getWidth(), getHeight(), null);g.drawString("你好", 100, 100);}

如果有区别的话,我也会使用 JFrame 而不是 JPanel 或组件.

Also I'm using a JFrame instead of JPanel or component if that makes a difference.

推荐答案

JFrame 没有 paintComponent 方法.您应该避免直接在框架上绘画,而是使用 JPanel 并覆盖其 paintComponent 方法

JFrame does not have a paintComponent method. You should avoid painting directly to a frame and instead use a JPanel and override its paintComponent method

您还应该使用@Override 注解,如果父类没有您尝试覆盖的方法,它将引发编译器异常...

You should also make use of the @Override annotation, which will raise a compiler exception if the parent class does not have the method you are trying to override...

相关文章