import javax.swing.*; public class JavaFrame extends JFrame { public void showFrame(){ //窗口的标题 this.setTitle("JavaFrame"); //窗口的位置与大小 this.setBounds(350,300,300,250); //建立一个“账户”标签 javax.swing.JLabel user = new javax.swing.JLabel("账户:"); //建立一个“密码”标签 javax.swing.JLabel pwd = new javax.swing.JLabel("密码:"); //建立一个账户输入框 javax.swing.JTextField tf = new javax.swing.JTextField(10); //建立一个密码输入框 javax.swing.JPasswordField pw = new javax.swing.JPasswordField(10); //建立一个“登陆”按钮 javax.swing.JButton jb = new javax.swing.JButton("登陆"); //在窗口上添加组件 this.setLayout(null); this.add(user); this.add(tf); this.add(pwd); this.add(pw); this.add(jb); //设置组件的坐标 user.setBounds(50, 30, 100, 30); tf.setBounds(110, 30, 120, 25); pwd.setBounds(50, 80, 100, 30); pw.setBounds(110, 80, 120, 25); jb.setBounds(90, 120, 100, 30); //建立监听 FrameListener fl = new FrameListener(jb,tf,pw); jb.addActionListener(fl); //窗口可见 this.setVisible(true); //关闭窗口时退出程序 this.setDefaultCloseOperation(3); } //程序入口 public static void main(String args[]){ JavaFrame jf = new JavaFrame(); jf.showFrame(); } }
import java.awt.event.ActionEvent; import javax.swing.*; public class FrameListener implements java.awt.event.ActionListener { private JButton jb; private JTextField tf; private JPasswordField pw; //构造器传参 public FrameListener(JButton jb,JTextField tf,JPasswordField pw){ this.jb = jb; this.tf = tf; this.pw = pw; } public void actionPerformed(ActionEvent e) { System.out.println("监听被触发"); String pWord = new String(pw.getPassword()); if(tf.getText().equals("user")&&pWord.equals("123")){ System.out.println("哈哈哈,我终于登陆进来啦!"); }else{ System.out.println("您的账户或密码错误,请仔细核对后再登陆。"); } } }