简体   繁体   中英

PaintComponent in JPanel not being called

I'm writing an Java Application and trying to paint an BufferedImage. In my main, the JFrame is being created and the JPanel is being created and is being added to the 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. I've googled this a lot, but i found nothing to solve my problem.

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:

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:

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.

Restructure your code. The creation of the panel should be done in the Frame class, not Main class.

Also, use a better name instead of Frame. The AWT already has a class called Frame so you name is very confusing. Make your class name more descriptive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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