/ * JDialog就是答案* /我看到有两种方法可以添加额外的窗口,使用JDialog,但是那些你不能放容器。或者将JInternalFrames与JDesktopPane这样的特定容器一起使用,但为此你必须将接口的所有其余部分转换为内部框架。添加类似JInternalFrame的窗口的最轻微方法是什么,对底层布局进行尽可能少的修改?
答案 0 :(得分:3)
JDialog具有与JFrame类似的contentPanes,您可以将任何放入JFrame的组件放入JDialog中。例如:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogEg {
private static void createAndShowGUI() {
MainPanelGen mainPanelGen = new MainPanelGen();
JFrame frame = new JFrame("DialogEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanelGen.getMainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class MainPanelGen {
private JPanel mainPanel = new JPanel();
private JTextField field = new JTextField(10);
private JButton btn = new JButton(new BtnActn());
private JDialog dialog;
private DialogPanel dialogPanel = new DialogPanel();
public MainPanelGen() {
mainPanel.add(field);
mainPanel.add(btn);
field.setEditable(false);
field.setFocusable(false);
}
public JPanel getMainPanel() {
return mainPanel;
}
private class BtnActn extends AbstractAction {
BtnActn() {
super("Button");
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (dialog == null) {
Window win = SwingUtilities.getWindowAncestor(mainPanel);
if (win != null) {
dialog = new JDialog(win, "My Dialog",
Dialog.ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true); // here the modal dialog takes over
System.out.println (dialogPanel.getFieldText());
field.setText(dialogPanel.getFieldText());
}
}
}
class DialogPanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton exitBtn = new JButton(new ExitBtnAxn("Exit"));
public DialogPanel() {
add(field);
add(exitBtn);
}
public String getFieldText() {
return field.getText();
}
private class ExitBtnAxn extends AbstractAction {
public ExitBtnAxn(String name) {
super(name);
}
@Override
public void actionPerformed(ActionEvent arg0) {
Window win = SwingUtilities.getWindowAncestor(DialogPanel.this);
if (win != null) {
win.dispose();
}
}
}
}