编写GUI程序,完成登录页面的设计
PS:作业记录1,“用户登录”不打空格无法使其显示在正中,注意改进。
作业要求:
编写GUI程序,完成登录界面的设计(使用绝对布局,图片自选)。当点击登录按钮时:如果输入的用户名和密码正确,则弹出“登录成功!”的对话框,否则显示“登录失败,请重新登录!”的对话框;如果输入为空,则显示“不能为空!”的对话框。当点击取消按钮时:退出登录界面。
程序完成展示图
上图是敲完下列代码后应有的样子。
代码如下
package L;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LaoFuLiaoFa1 extends JFrame{
private JPanel jpanel1,jpanel2,jpanel3;
private JTextField name;
private JPasswordField password;
private JLabel label1,label2,jLabel;
private JButton button1,button2;
private String welcom=" 用户登录";
private JLabel Welcome=new JLabel(welcom);
public LaoFuLiaoFa1(){
this.setTitle("登录界面");
Container picture=this.getContentPane();
picture.setLayout(new BorderLayout());
jLabel=new JLabel(new ImageIcon("C:\\Users\\Admin.DESKTOP-OSCOCKM\\lsj\\奥特曼.jpg"));//这里的路径为绝对路径
jpanel1 = new JPanel();
jpanel2 = new JPanel();
jpanel3 = new JPanel();
label1 = new JLabel("用户名:");
label2 = new JLabel("密 码:");
button1= new JButton(" 登 录 ");
button2 = new JButton(" 取 消 ");
//设置监听和登录框
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(name.getText().length()==0||new String(password.getPassword()).length()==0)
JOptionPane.showMessageDialog(null, "不能为空!");
else if(name.getText().equals("老夫撩发")&&new String(password.getPassword()).equals("777"))
JOptionPane.showMessageDialog(null, "登录成功!");
else
JOptionPane.showMessageDialog(null, "登陆失败,请重新登录!");
}
});
//设置监听和取消框
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
picture.add(jLabel,BorderLayout.NORTH);
this.add(Welcome);
name = new JTextField(20);//设置用户名框长度
password = new JPasswordField(20);//设置密码框长度
this.setLayout(new GridLayout(5,1));//设置布局
this.add(jpanel1);
this.add(jpanel2);
this.add(jpanel3);
jpanel1.add(label1);
jpanel1.add(name);
jpanel2.add(label2);
jpanel2.add(password);
jpanel3.add(button1);
jpanel3.add(button2);
this.setSize(300,400);
this.setResizable(false);
this.setLocation(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
LaoFuLiaoFa1 lsj= new LaoFuLiaoFa1();
}
}