1

I am facing a strange problem with a simple JFrame application which has only one button in order to change a field value. When I try to debug my application, it works fine, but when I try to run it, it doesn't work and gets stuck in the while loop. This is my graphics class:

public class Test extends JFrame implements ActionListener
{
    private static final long serialVersionUID = 1L;
    private boolean connectPressed;
    public JButton btnConnect;
    public Test()
    {
        JPanel p = new JPanel();
        p.setLayout(null);

        // connect button
        btnConnect = new JButton("connect");
        btnConnect.setBounds(0, 0, 100, 20);
        p.add(btnConnect);
        btnConnect.addActionListener(this);     


        getContentPane().add(p);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("Client");
        setSize(200,200);
        setVisible(true);
    }

    public boolean get()
    {
        //System.out.println(connectPressed);
        return connectPressed;
    }

    public void set(boolean b)
    {
        connectPressed = b;
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        //e.getActionCommand();
        connectPressed = true;
        System.out.println(connectPressed);
    }

}

and here is my Test code for the application:

public class Test2
{
    public static void main(String[] args)
    {
        System.out.println("Hello");
        Test t = new Test();

        t.set(false);
        while (true)
        {
            if ((t.get()))
                break;              
        }
        System.out.println("Bye");

    }

}

Can anyone help me what is the problem?

guido
  • 18,864
  • 6
  • 70
  • 95

1 Answers1

1

When you run this:

while (true) {
    if ((t.get()))
        break;              
}

the thread will eat all cpu, making the UI unresponsive; to overcome, one easy way would be adding a sleep time inside the loop:

while (true) {
    Thread.sleep(250); // sleep for 250 msecs
    if (t.get())
        break;              
}

Anyway it is just an example, not really a solution; a better way would be registering your main class as a listener, or running the loop in a separated thread.

Community
  • 1
  • 1
guido
  • 18,864
  • 6
  • 70
  • 95