【问题标题】:Can't Show JOptionPane - Java Swing无法显示 JOptionPane - Java Swing
【发布时间】:2015-01-25 12:32:52
【问题描述】:

我是 Java 新手。我需要你的帮助。

我的代码运行良好,直到它显示 JDialog。我有一个显示消息对话框的按钮 (JOptionPane)。单击按钮时存在问题。消息对话框似乎没有出现。它更像是卡住了,无法关闭,必须从我的 Eclipse 中终止。

请谁能告诉我为什么JOptionPane 不能显示?而且我不知道它的参数上parentComponent是什么意思。

这是我的代码。

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?");

    }

}

【问题讨论】:

  • 避免使用setLayout (null),除非非常需要

标签: java swing joptionpane jdialog


【解决方案1】:

首先,您需要在initComp 中添加以下语句,以便JFrame 可见:

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

    ...
}

显示对话框时,将父组件设置为当前的JFrame,以便它显示在框架本身中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 2012-09-24
    相关资源
    最近更新 更多