signalmarkp
signalmarkp

Reputation: 19

Swingutilities.invokeLater and while loop

my prog uses a frame and a panel, which are created once in a loop. The frame gets created and displayed as normal, but for some reason the panel is not created and/or it is not displayed.

any thoughts.

cheers.

class GUIThread extends Thread
{
    public boolean threadClose;

    public GUIThread()
    {
        SwingUtilities.invokeLater(this);
    }
    @Override
    public void run()
    {
        JFrame lFrame = null;
        JPanel lPanel = null;
        boolean lFrameFlag = false;

        threadClose =  false;

        while( !threadClose )
        {
            if(lFrameFlag == false)
            {
                lPanel = new JPanel();
                lPanel.setSize(580,356);
                lPanel.setLocation(10,10);
                lPanel.setVisible(true);
                lPanel.setBorder( BorderFactory.createLineBorder(Color.BLACK) );

                lFrame = new JFrame();
                lFrame.setSize(600,400);
                lFrame.setLocation(200,200);
                lFrame.add(lPanel);
                lFrame.setVisible(true);

                lFrameFlag = true;
            }
        }
    }
}

public class GUITestHarness
{
    public static void main(String[] args)
    {
        GUIThread lGUIThread = new GUIThread();
    }
}

when running the frame is displayed, but the panel is not.

Upvotes: 0

Views: 201

Answers (1)

Tobias
Tobias

Reputation: 2575

The problem is the while loop. The panel would be displayed if the execution would continue, but since the while loop is an infinte loop the frame is never updated, because the execution is stuck in the loop.

So if you try without the infinite loop it should work. Like this:

import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

//here it's better to implement Runnable than extend Thread
//in this case it's the same, but extending thread can lead to strange problems in other cases
public class Frame implements Runnable {

    public static void main(String[] args) {
        new Frame();
    }

    public Frame() {
        SwingUtilities.invokeLater(this);
    }

    @Override
    public void run() {
        JFrame lFrame = null;
        JPanel lPanel = null;

        lPanel = new JPanel();
        lPanel.setSize(580, 356);
        lPanel.setLocation(10, 10);
        lPanel.setVisible(true);
        lPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        lFrame = new JFrame();
        lFrame.setSize(600, 400);
        lFrame.setLocation(200, 200);
        lFrame.add(lPanel);
        lFrame.setVisible(true);

    }
}

Upvotes: 1

Related Questions