import javax.swing.*;
import java.awt.*; //导入必要的包
public class Home extends JFrame{
private JPanel jPanel=new JPanel();//用于放登陆信息面板
JTextField jTextField ;//定义登录名文本框组件
JPasswordField jPasswordField;//定义密码框组件
JLabel jLabel1,jLabel2;
JPanel jp1,jp2,jp3;
JButton jb1,jb2; //创建按钮
public Home(){
jTextField = new JTextField(13);
jPasswordField = new JPasswordField(13);
jLabel1 = new JLabel("用户名:");
jLabel2 = new JLabel("密码:");
jb1 = new JButton("登陆");
jb2 = new JButton("取消");
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
//设置布局
this.setLayout(new GridLayout(3,1));
jp1.add(jLabel1);
jp1.add(jTextField);//第一块面板添加用户名和文本框
jp2.add(jLabel2);
jp2.add(jPasswordField);//第二块面板添加密码和密码输入框
jp3.add(jb1);
jp3.add(jb2); //第三块面板添加确认和取消
// jp3.setLayout(new FlowLayout()); //因为JPanel默认布局方式为FlowLayout,所以可以注销这段代码.
jPanel.setBorder((BorderFactory.createTitledBorder("请输入登陆信息")));//设置标题样式
jPanel.add(jp1);
jPanel.add(jp2);
jPanel.add(jp3); //将三块面板添加到登陆框上面
jPanel.setSize(600,100);//设置登陆面板的大小
this.add(jPanel);
//设置显示
this.setSize(600, 300);
//this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setTitle("2015 求回家!!!");
}
public static void main(String[] args){
new Home();
}
}
Java用户登陆这块,主要还是学到了新的类:
1,边界布局:BorderLayout。他主要分为五个布局,是JFrame(顶层容器),JDialog(创建对话框窗口的类)的默认布局方式。其最多容量为5个组件,超出5个得用其他的。设置方式为:BorderLayout.NORTH;BorderLayout.SOUTH;BorderLayout.CENTER;Borderlayout.CENTER;BorderLayout.LEFT;BorderLayout.RIGHT。
2,流式布局:FlowLayout。布局方式为从左到右,从上到下。是JPanel(轻量级容器)的默认面板布局。
3,网格布局:GridLayout。布局方式为行和列组成的网络。布局方法:setLayout(new GridLayout(3,2,3,3));其中强两位数字表示三行两列,后两位表示行与行的间距为3,列与列的间距为3.
接着,就接触到JPanel面板。JPanel是非顶层容器,所以,一个界面只能由一个JFrame,但是可以有多个JPanel组件。其默认布局方式为流式布局。在JPanel这块,学到了用户登录界面的设计。从而接触到另外三个组件:文本框组件:JTextField;密码框组件:JPasswordField;标签组件:JLabel;复选框组件:JCheckBox;单选框组件:JRadioButton;按钮组件JButton。
根据上面的组件和布局方式,我试着做了如下效果的一些代码: