GUI
图形用户界面
CLI
命令行用户接口
Java为GUI提供的对象存在java.Awt和Javax.Swing两个包中.
Java当中如何完成图形化界面的制作呢?
AWT:abstract Window ToolKit.需要调用本地系统实现功能.属于重量级控件.依赖于平台.跨平台性不是特别好.
Javax.Swing:在AWT基础上.建立一套图形化系统,提供更多组件,完全由java实现,增强了可移植性,属于轻量级控件.所以以后最好用Swing开发.
还有一个SWT外观包.
Lable用来封装文字.CheckBox复选框.TextComponent:文本组件.
Container: 容器,是一个特殊的组件,可以通过add方法来添加其他组件进来.
Window:Frame框架.Dialog:对话框.FileDialog:文件对话框就是打负责文件的选取和保存的窗口.
容器中的组件的排放方式,就是布局.
Panel:面板
常见的布局管理器:
FlowLayout:流式布局管理器.先放中间.第二次放右边.默认居中.
从左到右.
Panel默认的布局管理器
BorderLayout:边界式布局
上下左右打麻将.如果不指定方向,那么会居中直接填满整个窗口.添加新组件就覆盖原组件.
GridLayout:网格式布局
每个组件都存放在格子当中,计算器就是一个GridLayout.
GridBagLayout:网格包布局管理器.
CardLayout:卡片式布局:
创建图形化界面:
1. 创建Frame窗体
2. 对窗体进行基本设置,比如大小位置和布局
3. 定义组件
4. 将组件通过窗体的add()添加到窗体中
5. 让窗体显示,通过setVisible(true);方法
事件监听机制:
1. 事件源:图形界面组件.
2. 事件:Event.每一个事件源都有自己的特有的对应事件和共性事件.
3. 监听器:可以触发某一个事件的动作都已经封装到了监听器中,
以上三者在Java中都定义好了,直接获取其对象就可以了.我们要做的事情就是对产生的动作进行处理.
添加监听器:f.add(WindowListener wl)
WindowListener的一个抽象子类 WindowAdapter,已经实现了接口,覆盖了其中所有方法,只要继承WindowAdapter覆盖自己需要的方法即可!
一般开发awt要导入两个包: java.awt.*;java.awt.event.*;
要让按钮具备退出的功能,那么按钮就是事件源,添加一个监听器.ActionListener是少数没有Adapter类的其中一个.因为它里面只有一个方法,直接实现即可.ActionPerfored(ActionEvent ae);
鼠标事件和键盘事件:
AddKeyListener
AddMouseListener
此时点击按钮谁会先执行?
鼠标动作先.
下面我们来动手做一些图形化界面:
实例1
package guiDemos;import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;public class AwtDemo1 {public static void main(String[] args) {Frame f = new Frame("my awt");f.setLayout(new FlowLayout());f.setVisible(true);f.setSize(300,200);f.setLocation(700, 400);Button b = new Button("我是一个按钮");//定义一个按钮,名称为"我是一个按钮"f.add(b);f.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e){System.out.println("我关!");System.exit(0); //点击右上角关闭按钮,退出虚拟机}public void windowActivated(WindowEvent e1){System.out.println("activated"); //每次窗口被激活,打印"activated"}public void windowOpened(WindowEvent e2){System.out.println("我活啦!"); //每次打开窗口,会输出"我活啦"}});System.out.println("hello world!");}
}
class myWindow extends WindowAdapter{public void windowClosing(WindowEvent e) {System.out.println("window closing");e.getWindow();System.out.println(e.toString());System.out.println(e.getWindow());System.out.println(e.getSource());System.exit(0);}
}
实例2
package guiDemos;import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;public class FrameDemo {public static void main(String[] args) {// TODO 自动生成的方法存根new Frame_Demo();}}class Frame_Demo {private Frame f;private Button but;Frame_Demo() {init();}public void init() {f = new Frame("myFrame");f.setBounds(1000, 500, 300, 400);f.setLayout(new FlowLayout());but = new Button("Run");myEvent();f.add(but);f.setVisible(true);but.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO 自动生成的方法存根System.out.println("button do");System.exit(0);}});}private void myEvent() {f.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}public void windowOpened(WindowEvent e) {System.out.println("活了");}});}
}
点击按钮,打印出
实例3
package guiDemos;import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;public class MouseKeyEventDemo {public static void main(String[] args) {// TODO 自动生成的方法存根new mouseAndKey();}}class mouseAndKey {private Frame f;private Button but;private TextField tf;mouseAndKey() {init();}public void init() {f = new Frame("myFrame");f.setBounds(1000, 500, 300, 400);f.setLayout(new FlowLayout());but = new Button("Run");tf = new TextField(20);myEvent();f.add(tf);f.add(but);f.setVisible(true);tf.addKeyListener(new KeyAdapter() {public void keyPressed(KeyEvent e) {int code = e.getKeyCode(); //判断输入的键值是否为数字if (!(code >= KeyEvent.VK_0 && code <= KeyEvent.VK_9)) {System.out.println(code+"is illegal");e.consume();}}});/** but.addActionListener(new ActionListener() {* * @Override public void actionPerformed(ActionEvent e) { // TODO* 自动生成的方法存根 System.out.println("button do"); System.exit(0); } });*/but.addMouseListener(new MouseAdapter() {public void mouseEntered(MouseEvent e) {System.out.println("entered");}public void mouseClicked(MouseEvent e) {if (e.getClickCount() == 2)System.out.println("双击动作");}});but.addKeyListener(new KeyAdapter() {public void keyPressed(KeyEvent e) {if (KeyEvent.getKeyText(e.getKeyCode()).equals("Q") && e.isControlDown())System.exit(0);System.out.println(KeyEvent.getKeyText(e.getKeyCode()) + "..." + e.getKeyChar());System.out.println("CTRL+Q");}});}private void myEvent() {f.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}public void windowOpened(WindowEvent e) {System.out.println("活了");}});}
}
实例4
package guiDemos;import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;public class MyMenuDemo {private Frame frame;private MenuBar bar;private Menu fileMenu, subMenu;private MenuItem closeItem, openItem, saveItem;private FileDialog openDlg, saveDlg;private TextArea ta;MyMenuDemo() {init();}public void init() {frame = new Frame("my Window");bar = new MenuBar();fileMenu = new Menu("文件");openItem = new MenuItem("打开");saveItem = new MenuItem("保存");closeItem = new MenuItem("退出");ta = new TextArea();openDlg = new FileDialog(frame, "打开文件", FileDialog.LOAD);saveDlg = new FileDialog(frame, "保存文件", FileDialog.SAVE);frame.add(ta);fileMenu.add(openItem);fileMenu.add(saveItem);fileMenu.add(closeItem);bar.add(fileMenu);frame.setMenuBar(bar);frame.setBounds(700, 300, 600, 500);frame.setVisible(true);closeItem.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO 自动生成的方法存根System.exit(0);}});openItem.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO 自动生成的方法存根openDlg.setVisible(true);String fileName = openDlg.getDirectory() + openDlg.getFile();if (openDlg.getFile() != null) {File f = new File(fileName);// File fileName = new File(openDlg.getFile());// ta.append(f.toString());ta.setText("");BufferedReader br = null;try {br = new BufferedReader(new FileReader(f));String line = null;while ((line = br.readLine()) != null) {ta.append(line + "\r\n");}} catch (IOException e1) {// TODO 自动生成的 catch 块e1.printStackTrace();} finally {try {if (br != null)br.close();} catch (IOException e1) {// TODO 自动生成的 catch 块e1.printStackTrace();}}}}});saveItem.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO 自动生成的方法存根saveDlg.setVisible(true);BufferedWriter bw = null;String fileName = saveDlg.getDirectory()+saveDlg.getFile();if(saveDlg.getFile()!=null){try {bw = new BufferedWriter(new FileWriter(fileName));String text = ta.getText();bw.write(text);} catch (IOException e1) {// TODO 自动生成的 catch 块e1.printStackTrace();}finally{try {if(bw!=null)bw.close();} catch (Exception e2) {// TODO: handle exception}}}}});frame.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});}public static void main(String[] args) {// TODO 自动生成的方法存根new MyMenuDemo();}}
选择文件后,文本区中显示文本内内容,相当于一个windows小工具记事本
实例5
写一个程序,用于遍历并文件夹中的所有内容
package guiDemos;import java.awt.Button;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;public class MyWindowDemo {private Frame frame;private TextField tf;private Button but;private TextArea ta;private Dialog dlg;private Label lbl;private Button butOK;MyWindowDemo() {init();}public void init() {frame = new Frame("my Window");frame.setBounds(900, 400, 400, 500);frame.setLayout(new FlowLayout());tf = new TextField(30);but = new Button("转到");ta = new TextArea(20, 40);frame.add(tf);frame.add(but);frame.add(ta);ta.setEditable(false);frame.setVisible(true);myEvent();tf.addKeyListener(new KeyAdapter() {public void keyPressed(KeyEvent e){if(KeyEvent.getKeyText(e.getKeyCode())=="Enter")doFile();}});but.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {doFile();}});}private void doFile(){ta.setText("");File f = new File(tf.getText());if (!f.exists()) {
// ta.setText("请重新输入地址");dlg = new Dialog(frame, "输入错误",false);lbl = new Label("\""+f.toString()+"\""+"不是一个有效路径");butOK = new Button("确定");dlg.setLayout(new FlowLayout());dlg.setBounds(900, 500, 300, 160);dlg.add(lbl);dlg.add(butOK);dlg.setVisible(true);dlg.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e){dlg.setVisible(false);}});butOK.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO 自动生成的方法存根dlg.setVisible(false);}});} elsefileList(f);}private void fileList(File f) {// TODO 自动生成的方法存根File[] files = f.listFiles();for (File file : files) {ta.append(file.toString());ta.append("\r\n");}/** for (File file : files) { if (!file.isHidden()) { if* (file.isDirectory()) { ta.append(file.toString()); ta.append("\r\n");* fileList(file); } else { ta.append(file.toString());* ta.append("\r\n"); // System.out.println(f); } } }*/}private void myEvent() {frame.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});}public static void main(String[] args) {// TODO 自动生成的方法存根new MyWindowDemo();}
}
以上就是Java awt界面的api基本使用.