我正在设计应用程序的GUI,而且我的Swing组件之间的通信存在一些问题。 我有一个MainGUI类,用户单击时必须创建一个新的JDialog对象并显示出来。 Dialog按我的意愿弹出,但它总是显示我上次访问时输入的先前值。如何防止这种行为和原因是什么?我想我在使用openActorDialog()函数时出错了。
public class MainGUI extends JPanel {
private ArrayList<Actor> actorList = new ArrayList<Actor>();
private JTextField field = new JTextField(10);
private JButton openDialogeBtn = new JButton("Open Dialog");
private String description;
// here my main gui has a reference to the JDialog and to the
// MyDialogPanel which is displayed in the JDialog
private JDialog dialog;
public MainGUI() {
setLayout(new BorderLayout(0, 0));
add(openDialogeBtn);
field.setEditable(false);
field.setFocusable(false);
add(field);
JMenuBar menuBar = new JMenuBar();
add(menuBar, BorderLayout.NORTH);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenu mnNew = new JMenu("New");
mnFile.add(mnNew);
JMenuItem mntmSystem = new JMenuItem("system");
mnNew.add(mntmSystem);
JMenuItem mntmUseCase = new JMenuItem("use case");
mnNew.add(mntmUseCase);
JMenuItem mntmActor = new JMenuItem("actor");
mnNew.add(mntmActor);
JTree tree = new JTree();
add(tree, BorderLayout.WEST);
/*
* Here we set the actions to be performed when the user interacts
*/
mntmActor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
openActorDialog();
}
});
}
private void openActorDialog() {
//Creation of the JDialog
CreateActorDialog createActorPanel = new CreateActorDialog();
if (dialog == null) {
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
dialog = new JDialog(win, "Create an actor", ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(createActorPanel);
dialog.setSize(500, 360);
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true); // here the modal dialog takes over
// this line starts *after* the modal dialog has been disposed
// **** here's the key where I get the String from JTextField in the GUI
// held
// by the JDialog and put it into this GUI's JTextField.
Actor a = new Actor(createActorPanel.getActorNameFromDialog(),
createActorPanel.getActorDescriptionFromDialog());
field.setText(createActorPanel.getActorNameFromDialog());
actorList.add(a);
System.out.println("It is written:" + createActorPanel.getActorDescriptionFromDialog());
for (Actor actor : actorList) {
System.out.println(actor.name + " with description :" + actor.description); // Will
// invoke
// override
}
}
}
答案 0 :(得分:2)
您必须在使用它之后或使用它之前再次将对话框设置为null,否则您将看到旧对话框。