Search code examples
javaswingjdialogevent-dispatch-thread

JDialog appearing without any content


So i've been having this problem with making my JDialog appear. I'm aware it's not a new question but i still can't quite grasp the concept of EDT, Concurrency in Swing. I'm hoping someone can explain this in an easy manner(or point me to some well explained resource) how does this work and how exactly would i include that in my code to make the JDialog work.

Here's the resource i was reading regarding Concurrency http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html

and here's my code:

public class TestView {

JFrame frame = new JFrame("Testing Radio Dialogs");
JPanel mainPanel = new JPanel();
JButton button = new JButton("Click me");
String[] folderNames = { "Java", "Ruby", "C++", "HTML" };

JRadioButton r11 = new JRadioButton(folderNames[0]);
JRadioButton r22 = new JRadioButton(folderNames[1]);
JRadioButton r33 = new JRadioButton(folderNames[2]);
JRadioButton r44 = new JRadioButton(folderNames[3]);

public TestView() {

    frame.add(mainPanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setSize(400, 400);
    mainPanel.setLayout(new GridLayout(0, 1));
    mainPanel.add(button);
    button.addActionListener(new ButtonListener());
    mainPanel.add(r11);
    mainPanel.add(r22);
    mainPanel.add(r33);
    mainPanel.add(r44);

}

class ButtonListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent ev) {
        if (ev.getSource() == button) {

            createPopup();

            System.out.println("Button clicked!");

        }

    }

}

public void createPopup() {

    JDialog dialog = new JDialog();
    JPanel dialogPanel = new JPanel(new GridLayout(0,1));
    dialogPanel.setSize(150, 150);      
    JRadioButton r1 = new JRadioButton("Ruby");
    JRadioButton r2 = new JRadioButton("Java");
    JRadioButton r3 = new JRadioButton("C++");
    JRadioButton r4 = new JRadioButton("HTML");
    ButtonGroup group = new ButtonGroup();
    group.add(r1);
    group.add(r2);
    group.add(r3);
    group.add(r4);
    dialogPanel.add(r1);
    dialogPanel.add(r2);
    dialogPanel.add(r3);
    dialogPanel.add(r4);
    dialog.setVisible(true);
    System.out.println("Popup created!");

}
}

I browsed through similar questions on different forums, but i'm still not quite grasping the concept. I'd appreciate any sort of feedback on this matter and my code.


Solution

  • No problems with concurrency or the dispatch thread, you just forgot to add dialogPanel to the dialog.

    public void createPopup() {
        //...
        dialog.add(dialogPanel);
        dialog.pack();
        dialog.setVisible();
        //...
    }