1

I have in my code the following method:

public String a(){
    String answer = null;
    JFrame frame = new JFrame();
    frame.setBounds(150, 150, 600, 600);
    JPanel p = new JPanel();
    p.setBackground(Color.red);
    JButton button = new JButton("button");
    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            answer = "answer";
        }
    });
    p.add(button);
    frame.add(p);
    frame.setVisible(true);
    while(answer == null){
        Thread.sleep(10);
    }
    return answer;
}

When I call this method from the main thread, everything shows normally, and the method works. But when I call it from the AWT_Thread the frame comes out completely blank.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
idan stark
  • 61
  • 1
  • 6
  • 1
    1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) Don't block the EDT (Event Dispatch Thread). The GUI will 'freeze' when that happens. See [Concurrency in Swing](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for details and the fix. 3) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Nov 14 '15 at 16:01
  • 1
    BTW - it looks like that entire frame would best be replaced with `JOptionPane.showInputDialog(..)` – Andrew Thompson Nov 14 '15 at 16:03
  • 1
    Swing is Single Threaded, see [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for more details – MadProgrammer Nov 20 '15 at 21:15

0 Answers0