黑马程序员——java第二十二天:GUI
2013-09-25 08:44
471 查看
------- android培训、java培训、期待与您交流! ----------
GUI
GUI——Graphical UserInterface(图形用户接口)。CLI——Command line UserInterface (命令行用户接口)就是常见的Dos命令行操作。
Java为GUI提供的对象都存在java.Awt和javax.Swing两个包中。
java.Awt:Abstract WindowToolKit (抽象窗口工具包),需要调用本地系统方法实现功能。属重量级控件。(快平台性较差)
javax.Swing:在AWT的基础上,建立的一套图形界面系统,其中提供了更多的组件,而且完全由Java实现。增强了移植性,属轻量级控件。
Container:为容器,是一个特殊的组件,该组件中可以通过add 方法添加其他组件进来。
布局
•FlowLayout(流式布局管理器)
从左到右的顺序排列。
Panel默认的布局管理器。
•
BorderLayout(边界布局管理器)
东,南,西,北,中
Frame默认的布局管理器。
•
GridLayout(网格布局管理器)
规则的矩阵
•
CardLayout(卡片布局管理器)
选项卡
•
GridBagLayout(网格包布局管理器)
非规则的矩阵(与网络布局管理器不同的是一个组件有可能占多个格子)
Frame
创建图形化界面1、创建Frame窗体
2、对窗体进行基本设置。比如:大小、位置、布局
3、定义组件
4、将组件通过窗体的add刚发添加到窗体中
5、让窗体显示。通过setvisible(true)
事件监听机制
创建图形化界面:1,创建frame窗体。
2,对窗体进行基本设置。
比如大小,位置,布局。
3,定义组件。
4,将组件通过窗体的add方法添加到窗体中。
5,让窗体显示,通过setVisible(true)
事件监听机制的特点:
1,事件源。
2,事件。
3,监听器。
4,事件处理。
事件源:就是awt包或者swing包中的那些图形界面组件。
事件:每一个事件源都有自己特有的对应事件和共性事件。
监听器:将可以触发某一个事件的动作(不只一个动作)都已经封装到了监听器中。
以上三者,在java中都已经定义好了。
直接获取其对象来用就可以了。
我们要做的事情是,就是对产生的动作进行处理。
窗体事件
窗口监听器:f.addWindowListener(WindowListener 1);说明:
WindowListener作为一个接口有7个方法需要实现者覆写。
WindowListener一个子类WindowAdapter为抽象类,他覆盖了父类的所有方法,但方法都为空。这样就可以继承WindowAdapter就方便创建侦听器对象和方法的书写(不可能只需要一个关闭窗口的动作,还要把所有的方法都覆写一遍吧)。
因为WindowListener在java.awt.event包中,所以图形化通常要导两个包awt和awt.event包
WindowListener中的方法:
windowClosing(WindowEvent e)关闭窗口动作方法
windowActivated(WindowEvente)激活窗口,每次窗口被激活就会执行这个方法中的动作(每次前置也是激活)。
windowOpened(WindowEvent e)当程序被打开是会执行这个动作。
Component中的方法:
void setBounds(int x,int y,int width,intheight);相当于setLacation()和setSize()两个方法。
getParent():获取此组件的父级。
validate():相当于刷新布局。(已经显示容器后,在修改此容器的子组件的时候,应调用此方法)
把图形化与事件分开:
1、在成员变量位置定义该图形中所需的组件引用:
例:private Frame=f;
2、在构造函数中调用生成图形化的方法,使对象已建立就具备这样的图形和事件功能。
例:init();
3、定义init方法(其方法中生成图形化界面,并加载事件方法)
一、对Frame进行基本设置
二、将组建添加到Frame中
三、加载一下窗体事件
四、显示窗体
4、定义事件方法(其中有监听的组件的方法事件)
按钮特有的监听器——addActionListeren.(中有待实现的方法actionPorformed(ActionEvent e);)
按钮是少数没有Adapter(适配器)其中一个。(一般方法超过三个就会有适配器,因为适配器覆写了接口中的所有方法(方法为空),有利于创建方法是覆写)
例子
package gui; import java.awt.*; import java.awt.event.*; public class AwtDemo { private Frame f; private Button b; public AwtDemo() { super(); init(); } private void init(){ //创建一个不可见得窗体,名字为awt f=new Frame("awt"); //设置窗体大小,x轴方向500,y轴方向400 f.setSize(500, 400); //设置窗体距离屏幕左上角的位置x轴相对位置300,y轴相对位置200 //f.setLocation(300, 200); //把Frame默认布局边界布局改为流式布局。 //f.setLayout(new FlowLayout()); //以上两个方法替换为 f.setBounds(300, 200, 500, 400); //创建名字“按钮”的按钮 b=new Button("关闭程序按钮按钮"); //把按钮添加进窗体中 f.add(b); myEvent(); //设置窗体可见 f.setVisible(true); } private void myEvent() { // TODO自动生成的方法存根 b.addActionListener(new ActionListener(){ int count=0; public void actionPerformed(ActionEvent e) { //System.out.println("按钮我关"); //System.exit(0); Button bu=(Button) e.getSource(); Frame f1=(Frame) bu.getParent(); f1.add(new Button("button"+count++)); //刷新当前布局 f1.validate(); } }); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.out.println("我关"); System.exit(0); } public void windowActivated(WindowEvent e){ System.out.println("激活"); } public void windowOpened(WindowEvent e){ System.out.println("打开了"); } }); } public static void main(String[] args) { new AwtDemo(); } }
鼠标键盘事件
鼠标键盘方法都在Component类中,因为所有组件都可以涉及到键盘鼠标事件。按钮有addActionListener(ActionListener l)监听,鼠标和键盘都能操作。
addMouseListener(MouseListenerl)监听,只间听鼠标对组件的操作。
当两者都存在监听单击时addMouseListener(MouseListener l)优先于addActionListener(ActionListener l)。
鼠标双击动作在MouseEvent类中有方法:e.getClickCount();//获取鼠标单击次数。
addKeyListener(Kyelistener l);方法多余三个所以有适配器类KeyAdapter。
Kyelistener接口中方法:keyPressed(KeyEvente);//按下某个键时调用此方法。
keyReleased(KeyEvent e);//释放某个键时调用此方法。
KeyEvent中方法:getKeyChar();返回为此按键事件定义的Unicode字符(可以理解为键盘上按下的键的字母)。
getKeyCode();返回键盘上实际键的整数代码(按下的键的代码)。
getKeyText(intkeyCode);返回物理键文本描述的字符串,物理键通过其keyCode标识(与getKeyChar()方法功能相同,只是字符串getKeyChar不能获取,并且他获得的是字符而不是字符串)。
在Event.InputEvent中有:
Boolean isControlDown()用于判段Ctrl键是否按下。(常用于组合键)。
void consume();使用此事件,以便不会按照默认的方式,有产生此事件的源代码来处理此事件(比如文本框不允许输入字母,就可以调用此方法,让其输不进字母)
例子
package gui; import java.awt.*; import java.awt.event.*; public class MouseAndKeyEvent { privateFrame f; privateButton but; privateTextField tf; MouseAndKeyEvent() { init(); } publicvoid init() { f= new Frame("my frame"); f.setBounds(300,100,600,500); f.setLayout(newFlowLayout()); tf= new TextField(20); but= new Button("my button"); f.add(tf); f.add(but); myEvent(); f.setVisible(true); } privatevoid myEvent() { //窗体关闭监听 f.addWindowListener(newWindowAdapter() { publicvoid windowClosing(WindowEvent e) { System.exit(0); } }); //文本框监听键盘输入监听 tf.addKeyListener(newKeyAdapter() { publicvoid keyPressed(KeyEvent e) { intcode = e.getKeyCode(); if(!(code>=KeyEvent.VK_0&& code<=KeyEvent.VK_9)) { System.out.println(code+".....是非法的"); e.consume(); } } }); //给But添加一个键盘监听。 but.addKeyListener(newKeyAdapter() { //案件监听 publicvoid keyPressed(KeyEvent e) { if(e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_ENTER) //System.exit(0); System.out.println("ctrl+enteris run"); //System.out.println(KeyEvent.getKeyText(e.getKeyCode())+"...."+e.getKeyCode()); } }); /**/ //对按钮监听(鼠标键盘都能操作) but.addActionListener(newActionListener() { publicvoid actionPerformed(ActionEvent e) { System.out.println("actionok"); } }); /**/ //鼠标监听(只有鼠标操作监听) but.addMouseListener(newMouseAdapter() { privateint count = 1; privateint clickCount = 1; //鼠标进入按钮范围监听(只有鼠标操作监听) publicvoid mouseEntered(MouseEvent e) { System.out.println("鼠标进入到该组件"+count++); } //鼠标双击监听 publicvoid mouseClicked(MouseEvent e) { if(e.getClickCount()==2) System.out.println("双击动作"+clickCount++); } }); } publicstatic void main(String[] args) { newMouseAndKeyEvent(); } }
对话框
对文本框清空操作:ta.setText();ta.append(String s);可以向文本框添加信息
Dialog类——对话框
构造函数其一——Dialog(Frame owner,String tile,Boolean model);
构造一个初始不可见的Dialog对话框,它带有指定的所有者Frame。标题和模式。
当模式为true时,弹出对话框后,所属后台框体不可操作。
让对话框不显示——d.setVisible(false);
例子:
import java.awt.*; import java.awt.event.*; import java.io.*; class MyWindowDemo { privateFrame f; privateTextField tf; privateButton but; privateTextArea ta; privateDialog d; privateLabel lab; privateButton okBut; MyWindowDemo() { init(); } publicvoid init() { f= new Frame("my window"); f.setBounds(300,100,600,500); f.setLayout(newFlowLayout()); tf= new TextField(60); but= new Button("转到"); ta= new TextArea(25,70); d= new Dialog(f,"提示信息-self",true); d.setBounds(400,200,240,150); d.setLayout(newFlowLayout()); lab= new Label(); okBut= new Button("确定"); d.add(lab); d.add(okBut); f.add(tf); f.add(but); f.add(ta); myEvent(); f.setVisible(true); } privatevoid myEvent() { okBut.addActionListener(newActionListener() { publicvoid actionPerformed(ActionEvent e) { d.setVisible(false); } }); d.addWindowListener(newWindowAdapter() { publicvoid windowClosing(WindowEvent e) { d.setVisible(false); } }); tf.addKeyListener(newKeyAdapter() { publicvoid keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_ENTER) showDir(); } }); but.addActionListener(newActionListener() { publicvoid actionPerformed(ActionEvent e) { showDir(); } }); f.addWindowListener(newWindowAdapter() { publicvoid windowClosing(WindowEvent e) { System.exit(0); } }); } privatevoid showDir() { StringdirPath = tf.getText(); Filedir = new File(dirPath); if(dir.exists()&& dir.isDirectory()) { ta.setText(""); String[]names = dir.list(); for(Stringname : names) { ta.append(name+"\r\n"); } } else { Stringinfo = "您输入的信息:"+dirPath+"是错误的。请重输"; lab.setText(info); d.setVisible(true); } } publicstatic void main(String[] args) { newMyWindowDemo(); } }
菜单
想Frame中添加(MenuBar)菜单条是通过setMenuBar添加的。把菜单添加在菜单条上。
Menu(菜单)下可以添加MenuIteam(子条目),也可以添加Menu(菜单)作为子菜单(当做为子菜单是会有箭头)。
例子:
import java.awt.*; import java.awt.event.*; class MyMenuDemo { privateFrame f; privateMenuBar mb; privateMenu m,subMenu; privateMenuItem closeItem,subItem; MyMenuDemo() { init(); } publicvoid init() { f= new Frame("my window"); f.setBounds(300,100,500,600); f.setLayout(newFlowLayout()); mb= new MenuBar(); m= new Menu("文件"); subMenu= new Menu("子菜单"); subItem= new MenuItem("子条目"); closeItem= new MenuItem("退出"); subMenu.add(subItem); m.add(subMenu); m.add(closeItem); mb.add(m); f.setMenuBar(mb); myEvent(); f.setVisible(true); } privatevoid myEvent() { closeItem.addActionListener(newActionListener() { publicvoid actionPerformed(ActionEvent e) { System.exit(0); } }); f.addWindowListener(newWindowAdapter() { publicvoid windowClosing(WindowEvent e) { System.exit(0); } }); } publicstatic void main(String[] args) { newMyMenuDemo(); } }
记事本
package gui; import java.awt.*; import java.awt.event.*; import java.io.*; public class MyMenuTest{ privateFrame f; privateMenuBar bar; privateTextArea ta; privateMenu fileMenu; privateMenuItem openItem,saveItem,closeItem; privateFileDialog openDia,saveDia; privateFile file; MyMenuTest() { init(); } publicvoid init() { f= new Frame("my window"); f.setBounds(300,100,650,600); bar= new MenuBar(); ta= new TextArea(); fileMenu= new Menu("文件"); openItem = new MenuItem("打开"); saveItem= new MenuItem("保存"); closeItem= new MenuItem("退出"); fileMenu.add(openItem); fileMenu.add(saveItem); fileMenu.add(closeItem); bar.add(fileMenu); f.setMenuBar(bar); openDia= new FileDialog(f,"我要打开",FileDialog.LOAD); saveDia= new FileDialog(f,"我要保存",FileDialog.SAVE); f.add(ta); myEvent(); f.setVisible(true); } privatevoid myEvent() { saveItem.addActionListener(newActionListener() { publicvoid actionPerformed(ActionEvent e) { //如果文件存在就不用弹出对话框了 if(file==null) { saveDia.setVisible(true); StringdirPath = saveDia.getDirectory(); StringfileName = saveDia.getFile(); //考虑取消问题 if(dirPath==null|| fileName==null) return; file= new File(dirPath,fileName); } try { BufferedWriterbufw = new BufferedWriter(newFileWriter(file)); Stringtext = ta.getText(); bufw.write(text); //bufw.flush(); bufw.close(); } catch(IOException ex) { thrownew RuntimeException(); } } }); openItem.addActionListener(newActionListener() { publicvoid actionPerformed(ActionEvent e) { openDia.setVisible(true); StringdirPath = openDia.getDirectory(); StringfileName = openDia.getFile(); // System.out.println(dirPath+"..."+fileName); if(dirPath==null|| fileName==null) return; ta.setText(""); file= new File(dirPath,fileName); try { BufferedReaderbufr = new BufferedReader(new FileReader(file)); Stringline = null; while((line=bufr.readLine())!=null) { ta.append(line+"\r\n"); } bufr.close(); } catch(IOException ex) { thrownew RuntimeException("读取失败"); } } }); closeItem.addActionListener(newActionListener() { publicvoid actionPerformed(ActionEvent e) { System.exit(0); } }); f.addWindowListener(newWindowAdapter() { publicvoid windowClosing(WindowEvent e) { System.exit(0); } }); } publicstatic void main(String[] args) { newMyMenuTest(); } }
/*
如何制作可以双击执行的jar包呢?
1,将多个类封装到了一个包(package)中。
2,定义一个jar包的配置信息。
定义一个文件a.txt 。文件内容内容为:
Main-Class:(空格)包名.类名(回车)
3,打jar包。
jar-cvfm my.jar a.txt 包名
4,通过winrar程序进行验证,查看该jar的配置文件中是否有自定义的配置信息。
5,通过工具--文件夹选项--文件类型--jar类型文件,通过高级,定义该jar类型文件的打开动作的关联程序。
jdk\bin\javaw.exe-jar
6,双击试试!。哦了。
------- android培训、java培训、期待与您交流! ----------详细请查看:http://edu.csdn.net
*/
相关文章推荐
- Example of how to wait for enqueued tasks to be completed:
- bochs安装freedos,以及host和guest系统拷贝文件
- 软件工程个人项目--Word frequency program
- Project: Individual Project - Word frequency program-11061154周辰光
- 关于软件工程个人作业 Word frequency program 的总结
- Individual Project - Word frequency program
- 代码实现UITextField收键盘
- UITextField的详细用法,包括具体协议(限制内容和大小等)
- UI控件之UIButton详解
- UI控件之UISlider用法
- 安装pt-query-digest
- Android中进程与线程及如何在子线程中操作UI线程
- KVC(key value coding)/ KVO(key value observing)
- [转]Web UI 设计命名规范
- Sublime Text增加Build system类型,打造一个全能IDE
- easyui datagrid 没数据时显示滚动条的解决方法
- easyui datagrid 没数据时显示滚动条的解决方法
- MySQL Query Log
- UVA - 11324 The Largest Clique
- Arduino入门笔记(3):单LED闪烁