我想创建一个将从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();
}
}
上面有一个Java教程。
从示例中:
new JDialog(this, "", Dialog.ModalityType.DOCUMENT_MODAL);