JDialog modal problem java gui

2019-07-07 18:56发布

问题:

I have this code which runs without any errors but it isn't running the way I planned. I'm trying to figure out why my "Continue" button is not being displayed when I click the button labeled "important!!".

The only thing which is being displayed is a blank pop up window which is part of the code JDialog and it set to modal and visible. I just can't figure it out. If anyone can help me I would appreciate it a lot.

JPanel hehePanel = new JPanel(new FlowLayout(FlowLayout.RIGHT,10,20));
JDialog dialog = new JDialog((JFrame)null);
dialog.getContentPane().add(hehePanel,BorderLayout.CENTER);
JButton hButton = new JButton("important!!");
JButton fButton = new JButton(" on construction !!");
JButton exitButton = new JButton("EXIT CAW ");
hehePanel.add(hButton);
hButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        final JPanel hehePanel = new JPanel();
        final JDialog dialog = new JDialog();
        dialog.getContentPane().add(hehePanel,BorderLayout.PAGE_END);
        dialog.toFront();
        dialog.setModal(true);
        dialog.pack();
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
        JButton closebutton = new JButton("Continue");
        closebutton.setActionCommand("continue");
        closebutton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if (evt.getActionCommand().equals("continue")) {
                    dialog.dispose();
                }
            }
        });
        hehePanel.add(closebutton);
    }
});

hehePanel.add(fButton);
hehePanel.add(exitButton);

回答1:

You need to add all the components to the dialog before making the dialog visible and before you pack() the dialog.

All the code after dialog.setVisible(true) does not execute until the dialog is closed.