与模式对话框进行数据交换

class PasswordChooser extends JPanel {
 public PasswordChooser() {
  this.setLayout(new BorderLayout());
  
  JPanel panel = new JPanel();
  panel.setLayout(new GridLayout(2, 2));
  panel.add(new JLabel("User name:"));
  panel.add(username = new JTextField(""));
  panel.add(new JLabel("Password:"));
  panel.add(password = new JPasswordField(""));
  this.add(panel, BorderLayout.CENTER);
  
  okButton = new JButton("Ok");
  okButton.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent event) {
    ok = true;
    dialog.setVisible(false);
   }
  });
  
  JButton cancelButton = new JButton("Cancel");
  cancelButton.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent event) {
    dialog.setVisible(false);
   }
  });
  
  JPanel buttonPanel = new JPanel();
  buttonPanel.add(okButton);
  buttonPanel.add(cancelButton);
  this.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.getRootPane().setDefaultButton(okButton);
   dialog.pack();
  }
  
  dialog.setTitle(title);
  dialog.setVisible(true);
  
  return ok;
 }
 
 private JTextField username;
 private JPasswordField password;
 private JButton okButton;
 private boolean ok;
 private JDialog dialog;
}

private class ConnectAction implements ActionListener {
  @Override
  public void actionPerformed(ActionEvent event) {
   if(dialog == null) {
    dialog = new PasswordChooser();
   }
   
   dialog.setUser(new User("Yourname", null));
   
   if(dialog.showDialog(DataExchangeFrame.this, "Connect")) {
    User u = dialog.getUser();
    textArea.append("User name = " + u.getName() + ", password = " + (new String(u.getPassword())) + "\n");
   }
  }
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值