真假问题
学编程时间不长,还没看设计模式,对下面这个程序中的 ok 真假的转换实在弄不明白
我的理解是 当okButton点击时 ok 为真
当有对象调用showDialog时 ok 是先变假 最后return ok 的时候 不一直应该是假吗?
可我在后面的程序中有看到 showDialog好像有变真的时候 请高人指点。谢谢
class PasswordChooser extends JPanel {
private JTextField username;
private JPasswordField password;
private JButton okButton;
private JDialog dialog;
private boolean ok;
public PasswordChooser() {
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 2));
panel.add(new JLabel("UserName: "));
panel.add(username = new JTextField(""));
panel.add(new JLabel("Password: "));
panel.add(password = new JPasswordField(""));
add(panel, BorderLayout.CENTER);
okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
ok = true;
dialog.setVisible(false);
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dialog.setVisible(false);
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
add(buttonPanel, BorderLayout.SOUTH);
}
public void setUser(User u) {
username.setText(u.getName());
}
public User getUser() {
return new User(username.getText(), password.getPassword());
}
public boolean showDialog(Component parent, String title) {
ok = false;
Frame owner = null;
if(parent instanceof Frame)
owner = (Frame) parent;
else
owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
if(dialog == null || dialog.getOwner() != owner) {
dialog = new JDialog(owner, true);
dialog.add(this);
dialog.setLocation(370, 300);
dialog.getRootPane().setDefaultButton(okButton);
dialog.pack();
}
dialog.setTitle(title);
dialog.setVisible(true);
return ok;
}
}