[2021/8/20]每周一题-1
本帖最后由 不会起名字的我 于 2021-8-20 12:24 编辑Swing开发
仔细阅读下面这段代码,回答问题。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Demo extends JFrame {
private String username;
private String pwd;
private JButton login;
private JTextField inputusername;
private JPasswordField inputpwd;
public Demo() {
init();
}
void init() {
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Demo");
JLabel l1 = new JLabel("用户名");
JLabel l2 = new JLabel("密码");
add(l1);
add(getUsernameTextfield());
add(l2);
add(getPwdpasswordfield());
add(getloginButton());
}
private JButton getloginButton() {
login = new JButton("登录");
login.setSize(30, 20);
login.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (getUsernameTextfield().getText() == username) {
String password = String.valueOf(getPwdpasswordfield().getPassword());
if (password == pwd) {
JOptionPane.showMessageDialog(null, "登录成功!");
} else {
JOptionPane.showMessageDialog(null, "密码错误", "错误", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "不存在的用户名", "错误", JOptionPane.ERROR_MESSAGE);
}
}
});
return login;
}
private JTextField getUsernameTextfield() {
inputusername = new JTextField(10);
return inputusername;
}
private JPasswordField getPwdpasswordfield() {
inputpwd = new JPasswordField(10);
inputpwd.setEchoChar('*');
inputpwd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
login.doClick();
}
});
return inputpwd;
}
public static void main(String[] args) {
new Demo().setVisible(true);
}
}
你知道为什么运行后整个窗体都是一个按钮吗?
答案
**** Hidden Message ***** 催更!{:10_254:} 6 why
页:
[1]