JAVA的addComponent_Java JDialog.addComponentListener方法代码示例

import javax.swing.JDialog; //导入方法依赖的package包/类

/**

* Ask using a GUI for the username and password.

*/

private void readFromGUI() {

// Create fields for user name.

final JTextField usernameField = new JTextField(20);

usernameField.setText(this.username);

final JLabel usernameLabel = new JLabel("Username: ");

usernameLabel.setLabelFor(usernameField);

final JPanel usernamePane = new JPanel(new FlowLayout(FlowLayout.TRAILING));

usernamePane.add(usernameLabel);

usernamePane.add(usernameField);

// Create fields for password.

final JPasswordField passwordField = new JPasswordField(20);

passwordField.setText(this.password);

final JLabel passwordLabel = new JLabel("Password: ");

passwordLabel.setLabelFor(passwordField);

final JPanel passwordPane = new JPanel(new FlowLayout(FlowLayout.TRAILING));

passwordPane.add(passwordLabel);

passwordPane.add(passwordField);

// Create panel

final JPanel main = new JPanel();

main.setLayout(new BoxLayout(main, BoxLayout.PAGE_AXIS));

main.add(usernamePane);

main.add(passwordPane);

// Create and handle dialog

final JOptionPane jop = new JOptionPane(main, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);

final JDialog dialog = jop.createDialog("User name and password");

dialog.addComponentListener(new ComponentAdapter() {

public void componentShown(ComponentEvent e) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

if (usernameField.getText().isEmpty())

{

usernameField.requestFocusInWindow();

}

else

{

passwordField.requestFocusInWindow();

}

}

});

}

});

dialog.setVisible(true);

final Integer result = (Integer) jop.getValue();

dialog.dispose();

if (result.intValue() == JOptionPane.OK_OPTION) {

this.username = usernameField.getText();

final char[] pwd = passwordField.getPassword();

this.password = new String(pwd);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值