简体   繁体   中英

Can't Show JOptionPane - Java Swing

I am new to Java. And I need your help.

My code is working well until it shows JDialog . I have a button to show a message dialog ( JOptionPane ). The problem exist when the button is clicked. Message dialog doesn't seems to appear. It more like stuck, can't be closed and it must be terminated from my Eclipse.

Please anyone tell me why JOptionPane can't show? And I don't know what the meaning of parentComponent on its parameter.

Here is my code.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JOptionPane;

@SuppressWarnings("serial")
public class Test extends JDialog implements ActionListener {

    private JButton testPane = new JButton(" Test Pane ");

    Test() {

        initComp();

    }

    private void initComp() {

        this.setSize(300, 200);
        this.setLocationRelativeTo(null);
        this.setTitle("Test");
        this.setAlwaysOnTop(true);
        this.setResizable(false);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.setLayout(null);

        testPane.setBounds(47, 25, 200, 120);
        this.add(testPane);
        testPane.addActionListener(this);

    }

    @Override
    public void actionPerformed(ActionEvent arg0) {

        JOptionPane.showMessageDialog(null, "Does it show?");

    }

}

First, you need to add the following statement in initComp so that the JFrame gets visible:

private void initComp() {
    ...
    this.setVisible(true);  // add this to show the frame

    ...
}

When displaying the dialog, set the parent component to the current JFrame so that it gets displayed in the frame itself:

@Override
public void actionPerformed(ActionEvent arg0) {
    JOptionPane.showMessageDialog(this, "Does it show?");  // add this as parent
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM