一、创建以上界面
1、创建类名,继承JFrame,连接口ActionListener创建内部监视器
public class CollTest extends JFrame implements ActionListener{/*** */
2、自我理解:可以根据一共有多少行,按行来描写代码,例如:用户名、密码和确定(取消)是不同行,所以放在不同的JPanel,因此定义三个
JTextField是创建文本框;
JLabel是标签;
JButton是按钮,可以点击。
private static final long serialVersionUID = 1L;JLabel jl1 = new JLabel("用户名:");//标签JTextField jtf1 = new JTextField(20);JLabel jl2 = new JLabel("密 码:");JTextField jtf2 = new JTextField(20);JButton jb1 = new JButton("确 定");//按钮JButton jb2 = new JButton("取 消");JPanel jp1 = new JPanel();JPanel jp2 = new JPanel();JPanel jp3 = new JPanel();
重写CollTest()无参数方法
this.setLayout()是布局管理器,代码中实现网格布局管理器
this.setSize()获得窗口的长度
将全部加入到各自的JPanel当中,再加入到方法中,若不加入方法,则无法显示
public CollTest() {this.setLayout(new GridLayout(5,1));this.setSize(400,300);this.setTitle("QQ登录窗口");this.setLocationRelativeTo(null);//居中位置this.setDefaultCloseOperation(EXIT_ON_CLOSE);//去掉窗口同时停止运行jp1.add(jl1);jp1.add(jtf1);jp2.add(jl2);jp2.add(jtf2);jp3.add(jb1);jp3.add(jb2);this.add(new JLabel());this.add(jp1);this.add(jp2);this.add(jp3);this.add(new JLabel());jb1.addActionListener(this);jb2.addActionListener(this);}
3、实现监听器
实现监听器少不了这两行代码,若不写,则无法显示监听
jb1.addActionListener(this);
jb2.addActionListener(this);
@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif(e.getSource()==jb1) {StringBuffer p = new StringBuffer();p.append("用户名为:"+jtf1.getText()+"\n");p.append("密码为:"+jtf2.getText());JOptionPane.showMessageDialog(this,p);}if(e.getSource()==jb2) {System.exit(0);}}
按确定则出现用户名为多少,密码为多少
按退出则整个程序退出,停止运行
二、源代码如下
package cn.baokx.test;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;public class CollTest extends JFrame implements ActionListener{/*** */private static final long serialVersionUID = 1L;JLabel jl1 = new JLabel("用户名:");//标签JTextField jtf1 = new JTextField(20);JLabel jl2 = new JLabel("密 码:");JTextField jtf2 = new JTextField(20);JButton jb1 = new JButton("确 定");//按钮JButton jb2 = new JButton("取 消");JPanel jp1 = new JPanel();JPanel jp2 = new JPanel();JPanel jp3 = new JPanel();public CollTest() {this.setLayout(new GridLayout(5,1));this.setSize(400,300);this.setTitle("QQ登录窗口");this.setLocationRelativeTo(null);//居中位置this.setDefaultCloseOperation(EXIT_ON_CLOSE);//去掉窗口同时停止运行jp1.add(jl1);jp1.add(jtf1);jp2.add(jl2);jp2.add(jtf2);jp3.add(jb1);jp3.add(jb2);this.add(new JLabel());this.add(jp1);this.add(jp2);this.add(jp3);this.add(new JLabel());jb1.addActionListener(this);jb2.addActionListener(this);}
最后结果如下: