java----GUI编程
1 package com.cilinmengye.HouseWork5;
2
3 import javax.swing.*;
4 import java.awt.*;
5 import java.awt.event.ActionEvent;
6 import java.awt.event.ActionListener;
7
8 //继承JFrame实现界面
9 public class GUIClass01 extends JFrame implements ActionListener {
10 //事件源:
11 private JButton readyButton, exitButton;
12 private JLabel messageLabel;
13 private JTextField name;
14 private JPasswordField passWord;
15
16 public GUIClass01() {
17 //设置标题
18 super("这是我第一个简单GUI页面");
19
20 //设置相关布局
21 setSize(500, 100);
22 setBackground(Color.lightGray);
23 setLocation(300, 240);
24 setLayout(new FlowLayout());
25
26 //添加相关组件
27 add(new JLabel("用户名: "));
28 name = new JTextField(5);
29 add(name);
30
31 add(new JLabel("密码: "));
32 passWord = new JPasswordField(5);
33 add(passWord);
34
35 readyButton = new JButton("确定");
36 exitButton = new JButton("退出");
37 add(readyButton);
38 add(exitButton);
39
40 messageLabel = new JLabel(" ");
41 add(messageLabel);
42
43 //添加相关事件,将事件源与处理者联系起来
44 //this实现了事件处理方法ActionListener
45 readyButton.addActionListener(this);
46 exitButton.addActionListener(this);
47 //注意messageLabel就不用进行关联了,因为其不可以触发事件
48
49 //注意setVisible(true)一定要放在最后
50 setVisible(true);
51 }
52
53 //实现对应的事件处理:
54 public void actionPerformed(ActionEvent e) {
55 if (e.getSource() == readyButton) {
56 String key = String.valueOf(passWord.getPassword());
57 String userName = name.getText();
58 if (key.equals("834430027") && userName.equals("次林梦叶"))
59 messageLabel.setText("欢迎您的使用,次林梦叶");
60 else messageLabel.setText("用户名或密码错误");
61 //好像这个语句加不加都没问题?
62 /*setVisible(true);*/
63 } else if (e.getSource() == exitButton)
64 System.exit(0);
65 }
66 }
67
68 class App {
69 public static void main(String[] args) {
70 new GUIClass01();
71 }
72 }
对于GUI编程重点是要掌握其框架:
其有基本的三种界面布局:
设置布局为:JPanel或JFrame的继承者,xxx.setLayOut(布局方式);
1.FlowLayOut:流式布局,即默认组件放一行,如果一行上放不下,默认放到第二行
2.BorderLayOut:边界布局,默认布局,即将界面分成东南西北中,这几个方向,每个方向可放一个组件
add(组件,Border.NORTH);
3.GridLayOut:格式布局,new GridLayOut(r,c),r行c列
还有事件
ActionListener 点击事件:一般是implement ActionListener ,要实现public void actionPerformed(ActionEvent e){}
WindowAdapter 窗口事件:一般是 extends WindowAdapter
private class WindowImp extends WindowAdapter {
public void windowClosing(WindowEvent e) {
}
}
这样是当关闭窗口时可以进行的操作
一般添加事件是:事件源.addActionListener(实现事件者(即implements或extends的类))
还有常用组件:
比如标签:JLable,填空JTextField,按钮JButton等