如何创建模态JDialog?

时间:2013-10-27 17:33:50

标签: java swing main jdialog

我想创建一个将从JMenuItem调用的模态JDialog。我已经阅读了一些帖子并找到了一个例子(看起来很可爱)。在此示例中,主框架从main方法调用。如何创建类似的东西,但在main方法中只会被称为主类的构造函数?

例如:http://www.rsdn.ru/forum/java/3526582.1

更新:

我的代码:

import java.awt.event.*;
import javax.swing.*;

 public class JD extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JMenuBar menubar = new JMenuBar();
private JMenu menu = new JMenu("Options");
private JMenuItem item = new JMenuItem("Try this");
JLabel label = new JLabel("label");
JTextField text = new JTextField(10);
JPanel panel = new JPanel();
JButton b = new JButton("get and close");

JD() {
    super("Frame");
    setSize(200, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    menu.add(item);
    menubar.add(menu);
    setJMenuBar(menubar);
    item.addActionListener(this);
    setVisible(true);
}

public void actionPerformed(ActionEvent evnt) {
    Object source = evnt.getSource();
    if (source == item) {
        new Dialog(new JFrame());
    }
}

private class Dialog extends JDialog {
    private static final long serialVersionUID = 1L;

    Dialog(JFrame frame) {
        super(frame, true);
        setSize(200, 200);
        setLocationRelativeTo(null);
        panel.setLayout(null);
        label.setBounds(10, 10, 50, 15);
        panel.add(label);
        text.setBounds(60, 8, 50, 19);
        panel.add(text);
        add(panel);
        b.setBounds(40, 40, 100, 25);
        panel.add(b);
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evnt) {
                System.out.println(text.getText());
                dispose();
            }
        });
        setVisible(true);
    }
}

public static void main(String[] args) {
    new JD();
}
}

1 个答案:

答案 0 :(得分:2)

显然,您没有谷歌这个问题,因为有一个Java tutorial on it

来自示例:

new JDialog(this, "", Dialog.ModalityType.DOCUMENT_MODAL);