简体   繁体   English

无法显示JOptionPane-Java Swing

[英]Can't Show JOptionPane - Java Swing

I am new to Java. 我是Java新手。 And I need your help. 我需要你的帮助。

My code is working well until it shows JDialog . 在显示JDialog之前,我的代码运行良好。 I have a button to show a message dialog ( JOptionPane ). 我有一个按钮来显示消息对话框( 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. 它更像卡住了,无法关闭,必须从我的Eclipse中终止。

Please anyone tell me why JOptionPane can't show? 请有人告诉我为什么JOptionPane无法显示? And I don't know what the meaning of parentComponent on its parameter. 而且我不知道parentComponent的参数含义是什么。

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: 首先,您需要在initComp添加以下语句,以使JFrame可见:

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: 显示对话框时,将父组件设置为当前JFrame ,以使其显示在框架本身中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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