Search code examples
javajdialog

JDialog components won't show up


So I have the following code.

public class GraveyardFrame extends JDialog{

private List<JLabel> labelList = new ArrayList<>();
private List<Piece> pieces = new ArrayList<>();

public GraveyardFrame(final Player player) {
    setSize(300,300);
    setTitle("Graveyard Zone~ Watch out!!");
    setResizable(false);
    setModalityType(ModalityType.APPLICATION_MODAL);  
    setLocationRelativeTo(null);    
    setVisible(true);
    createView(player);   //here I add all the components
}

public void createView(Player player) {
    JPanel mainPanel = new JPanel(new FlowLayout());
    add(mainPanel);
    mainPanel.setBackground(new Color(128,64,0));
    createLabels(player ,mainPanel);   //here I add the labels, that will take the icon of the dead pieces
    this.pack();
}

private void createLabels(Player player , JPanel mainPanel) {
    pieces.addAll(player.getPlayerGraveyard());   //pieces holds all the dead pieces
    int sizeOfgraveyard = player.getPlayerGraveyard().size();

    for (int i = 0 ; i < sizeOfgraveyard ; i++) {
        JLabel label = new JLabel();
        label.setSize(60, 60);         
        label.setIcon(pieces.get(i).getIcon());
        labelList.add(label);
        mainPanel.add(label); 
        mainPanel.validate();
        mainPanel.repaint();
    }
}

It is supposed to pop up a JDialog that takes all the dead pieces of a chess player and display them. First I used a JFrame , but I find out that a JFrame can't wait for an action to happen and only then continue with the main GUI .(in JDialog , using ModalityType is enough ).

The problem is that it doesn`t show anything, just an empty JDialog box. I searched for this problem, and here somebody said that you should use validate() ,repaint() and pack() . I tried this, as in the code above, but still nothing happens

This is how it should look like (works with JFrame instead of JDialog) :fine This is how it actually looks like (with the code above) : not fine


Solution

  • You call setVisible(true) before createView(). But as it is a JDialog which is modal, calling setVisible() actually blocks until the dialog is dismissed. So, createView() will only be called once the dialog got closed.

    Just change the order of the two method calls, first createView() and next setVisible(true), and it should work.