简体   繁体   English

未调用JPanel中的PaintComponent

[英]PaintComponent in JPanel not being called

I'm writing an Java Application and trying to paint an BufferedImage. 我正在编写Java应用程序并尝试绘制BufferedImage。 In my main, the JFrame is being created and the JPanel is being created and is being added to the JFrame. 在我的主要内容中,正在创建JFrame并正在创建JPanel并将其添加到JFrame中。 There is also a Thread being started for repainting, but it shows nothing and my System.out.println() in the paintComponent isn't called, too. 还有一个Thread正在重新绘制,但它没有显示任何内容,并且我的paintComponent中的System.out.println()也没有被调用。 I've googled this a lot, but i found nothing to solve my problem. 我用Google搜索了很多,但我没有找到解决问题的方法。

What am i doing wrong and why is it wrong??? 我做错了什么,为什么这是错的?

My Code: 我的代码:

The main + Thread: 主+线程:

public class Main extends Thread
{
    public static Frame frame = new Frame();

    public static void main(String[] args) throws IllegalStateException, IOException
    {
        frame.activePanel = new LoginPanel();
        frame.add(frame.activePanel);

        new Main();
    }

    public Main()
    {
        this.start();
    }

    @Override
    public void run()
    {
        while(true)
        {
            if(Main.frame.activePanel != null)
                Main.frame.activePanel.repaint();

            try{Thread.sleep(15);}catch(InterruptedException e){}
        }
    }
}

The JFrame: JFrame:

public class Frame extends JFrame
{
    public JPanel activePanel = null;

    public Frame()
    {
        super();

        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setBounds(this.getToolkit().getScreenSize().width / 2 - 640,this.getToolkit().getScreenSize().height / 2 - 400,1279,799);
        this.setResizable(false);
        this.setUndecorated(true);
        this.setVisible(true);
    }
}

and the JPanel: 和JPanel:

public class LoginPanel extends JPanel
{
    BufferedImage loginImg;

    public LoginPanel() throws IOException
    {
        loginImg  = ImageIO.read(new File("src/images/Login.PNG"));
    }

    @Override
    protected void paintComponent(Graphics g)
    {System.out.println("painting");
        g.drawImage(loginImg, 0, 0, null);
    }
}

Looks to me like you are adding the panel to the frame AFTER the frame is visible. 在我看来,就像你在框架可见之后将面板添加到框架一样。 When you do this the layout manager is not invoked and the size of the panel is (0, 0) so there is nothing to paint. 执行此操作时,不会调用布局管理器,并且面板的大小为(0,0),因此无需绘制任何内容。

Restructure your code. 重构您的代码。 The creation of the panel should be done in the Frame class, not Main class. 面板的创建应该在Frame类中完成,而不是在Main类中完成。

Also, use a better name instead of Frame. 另外,使用更好的名称而不是Frame。 The AWT already has a class called Frame so you name is very confusing. AWT已经有一个名为Frame的类,所以你的名字很混乱。 Make your class name more descriptive. 使您的班级名称更具描述性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM