33、GUI
概述
GUI(Graphical User interface)图形用户接口
用图形的方式,来显示计算机操作的界面,这样更方便,更直观
CLI(Command Line User Interface)命令行用户接口
就是常见的DOS命令行操作,需要记忆一些常用的指令,操作不直观
举例:比如创建文件夹,或者删除文件夹
Java为GUI提供的对象都存在Java.awt和Java.swing两个包中
Awt和Swing
Java.Awt: Abstract Windows Toolkit(抽象窗口工具包)需要调用本地系统实现功能,属于重量级控件
Java.Swing:在AWT基础上,建立一套图形界面系统,其中提供了更多的组件,而且完全由Java实现,增强了移植性,属于轻量级控件
名词解释
Component——组件
Contaner——容器——是一个特殊的组件,该组件可以通过add方法添加其他组件进来
Window——窗口
Panel——面板
Frame——框架
Dialog——对话框
FileDialog——文件对话框
Button——按钮
Label——标签
CheckBox——复选框
TextArea——文本框
TextField——文本区
布局
容器中的组件的排列方式——布局
常见的布局管理器
FlowLayout——流式布局管理器,从左到右顺序排列,Panel默认的布局管理器
BorderLayout——(东、南、西、北、中,Frame默认的布局管理器)
GridLayout——网格布局管理器,规则的矩阵
CardLayout——卡片布局管理器,选项卡
GridBayLayout——网格布局管理器,非规则的矩阵
Frame
创建图形界面的步骤
1、创建Frame窗体
2、对窗体进行基本设置,比如大小、位置、布局
3、定义组件
4、将组件通过窗体的add方法添加到窗体中
5、让窗体显示,通过setVisable(true)
package swin;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;
//VS4E -- DO NOT REMOVE THIS LINE!
public class AutoDemo extends JFrame {
private static final long serialVersionUID = 1L;
private JButton jButton0;
private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
public AutoDemo() {
initComponents();
}
private void initComponents() {
setLayout(new GroupLayout());
add(getJButton0(), new Constraints(new Leading(139, 10, 10), new Leading(131, 10, 10)));
setSize(320, 240);
}
private JButton getJButton0() {
if (jButton0 == null) {
jButton0 = new JButton();
jButton0.setText("按钮");
jButton0.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
jButton0MouseMouseClicked(event);
}
});
}
return jButton0;
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class.
* Note: This class is only created so that you can easily preview the result at runtime.
* It is not expected to be managed by the designer.
* You can modify it as you like.
*/
public static void main(String[] args) {
installLnF();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
AutoDemo frame = new AutoDemo();
frame.setDefaultCloseOperation(AutoDemo.EXIT_ON_CLOSE);
frame.setTitle("AutoDemo");
frame.getContentPane().setPreferredSize(frame.getSize());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private void jButton0MouseMouseClicked(MouseEvent event)
{
System.out.println("你好!GUI");
}
}
事件监听机制
1、将监听器注册到事件源
2、有监听器所监听的动作作于事件源点
3、产生事件对象
4、将事件对象传给事件处理方式
事件监听机制的特点
1、事件源:awt包或者swing包中的图形界面组件
2、事件:每一个事件源都有自己特有的对应事件和共性事件
3、事件监听器:将可以触发某一个事件的动作都已经封装到了监听器中
4、事件处理:我们要做的就是对产生的动作进行处理
(前三条Java中已经定义好了,直接获取对象就可以了)
事件分类
MouseEvent 鼠标事件
WindowsEvent 窗口事件
ActionEvent 动作事件
按事件性质分类
低级事件
语义事件(又叫高级事件)
事件注意
1、一个事件监听器对象负责处理一类事件
2、一类事件的每一种发生情况,分别由事件监听器对象中的一个方法来具体处理
3、在事件源和事件监听器对象中进行约定的接口类,被称为事件监听器接口
4、事件监听器接口类名称与事件类的名称相对应,例如MouseEvent事件类的监听器接口为MouseListener
处理发生在GUI组件上的XX Event事件的某种情况,用事件处理的通用编写流程
1、编写一个实现XXXListener接口的事件监听器类
2、XXXListener类中用于处理该事件情况的方法中,编写处理代码
3、调用组件add XXXListener方法,将类XXXListener创建的实例对象注册到GUI组件上
事件适配器
JDK中也提供了大多数事件监听器接口的最简单的实现类,称之为适配器 Adapter类
用事件适配器处理事件,可以简化事件监听器编写
初学者使用事件适配器时的常见问题和解决问题的思路
1、是方法没被调用还是程序代码的执行问题
2、是方法名写错了,还是没有注册事件监听器
package days18;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class Awt
{
public static void main(String[] args)
{
Frame f = new Frame("my awt");
f.setSize(500,400);
f.setLocation(300,200);
f.setLayout(new FlowLayout());
Button b = new Button("我是一个按钮");
f.add(b);
f.addWindowListener(new WindowAdapter()
{
public void windowOpened(WindowEvent e)
{
System.out.println("我开了!!!");
}
public void windowClosing(WindowEvent e)
{
System.out.println("我关了");
System.exit(0);
}
});
f.setVisible(true);
System.out.println("Hello World!");
}
}
事件处理的多重应用
1、如何知道一个GUI组件到底能够触发哪几种事件
2、一个组件上的一个动作可以产生多种不同类型的事件
3、一个事件监听器对象可以注册到多个事件源上
4、在一个事件源上也可以注册同一类事进行处理的多个事件监听器对象
package days18;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class Fra
{
public static void main(String[] args)
{
Frame f = new Frame("my awt");
f.setSize(500,400);
f.setLocation(300,200);
f.setLayout(new FlowLayout());
Button b = new Button("退出按钮");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("按钮退出!!");
System.exit(0);
}
});
f.add(b);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.out.println("我关了");
System.exit(0);
}
});
f.setVisible(true);
}
}
让按钮具备退出程序的功能,按钮是事件源,那么选择哪个监听器,通过关闭窗口示例了解到,想要知道哪个组件具备什么样特有的监听器,需要查看该组件对象的功能,通过查阅button的描述,发现按钮支持一个特有的监听器 addActionListener
键盘鼠标事件
package days18;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;
//VS4E -- DO NOT REMOVE THIS LINE!
public class MK extends JFrame {
private static final long serialVersionUID = 1L;
private JButton jButton0;
public MK() {
initComponents();
}
private void initComponents() {
setLayout(new GroupLayout());
add(getJButton0(), new Constraints(new Leading(10, 10, 10), new Leading(138, 10, 10)));
add(getJTextField0(), new Constraints(new Leading(38, 215, 10, 10), new Leading(37, 10, 10)));
setSize(320, 240);
}
private JTextField getJTextField0() {
if (jTextField0 == null) {
jTextField0 = new JTextField();
jTextField0.setText("随便写几个字吧。。。");
jTextField0.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
jTextField0KeyKeyPressed(event);
}
});
}
return jTextField0;
}
private JButton getJButton0() {
if (jButton0 == null) {
jButton0 = new JButton();
jButton0.setText("按钮");
jButton0.setRolloverEnabled(false);
jButton0.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
jButton0MouseMouseClicked(event);
}
});
}
return jButton0;
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class.
* Note: This class is only created so that you can easily preview the result at runtime.
* It is not expected to be managed by the designer.
* You can modify it as you like.
*/
public static void main(String[] args) {
installLnF();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MK frame = new MK();
frame.setDefaultCloseOperation(MK.EXIT_ON_CLOSE);
frame.setTitle("MK");
frame.getContentPane().setPreferredSize(frame.getSize());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private void jButton0ActionActionPerformed(ActionEvent event)
{
System.out.println("鼠标来了!!");
}
int s=1;
private JTextField jTextField0;
private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
private void jButton0MouseMouseClicked(MouseEvent event)
{
System.out.println("鼠标进入该组件,鼠标双击键退出"+s++);
if(event.getClickCount()==2)
{
System.exit(0);
}
}
private void jTextField0KeyKeyPressed(KeyEvent e)
{
if(e.getKeyCode()==e.VK_BACK_SPACE)
{
System.exit(0);
}
}
}
package days18;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;
public class MU extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField tf;
private JButton but;
private JTextArea ta;
private JScrollPane jScrollPane0;
private JLabel lb0;
private JLabel lb1;
private JLabel jLabel0;
private JLabel jLabel2;
private JLabel jLabel1;
private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
public MU() {
initComponents();
}
private void initComponents() {
setLayout(new GroupLayout());
add(gettf(), new Constraints(new Leading(27, 477, 10, 10), new Leading(54, 27, 12, 12)));
add(getbut(), new Constraints(new Leading(531, 10, 10), new Leading(53, 12, 12)));
add(getJScrollPane0(), new Constraints(new Leading(26, 586, 12, 12), new Leading(149, 227, 10, 10)));
add(getJLabel0(), new Constraints(new Leading(27, 85, 10, 10), new Leading(29, 12, 12)));
add(getJLabel2(), new Constraints(new Leading(29, 10, 10), new Leading(93, 12, 12)));
add(getJLabel1(), new Constraints(new Leading(29, 83, 12, 12), new Leading(125, 12, 12)));
add(getlb1(), new Constraints(new Leading(97, 87, 10, 10), new Leading(93, 12, 12)));
setSize(640, 400);
}
private JLabel getJLabel1() {
if (jLabel1 == null) {
jLabel1 = new JLabel();
jLabel1.setText("浏览目录:");
}
return jLabel1;
}
private JLabel getJLabel2() {
if (jLabel2 == null) {
jLabel2 = new JLabel();
jLabel2.setText("所花时间");
}
return jLabel2;
}
private JLabel getJLabel0() {
if (jLabel0 == null) {
jLabel0 = new JLabel();
jLabel0.setText("查询地址:");
}
return jLabel0;
}
private JLabel getlb1() {
if (lb1 == null) {
lb1 = new JLabel();
//lb1.setText(" ");
}
return lb1;
}
private JLabel getlb0() {
if (lb0 == null) {
lb0 = new JLabel();
lb0.setText("所花时间:");
}
return lb0;
}
private JScrollPane getJScrollPane0() {
if (jScrollPane0 == null) {
jScrollPane0 = new JScrollPane();
jScrollPane0.setViewportView(getta());
}
return jScrollPane0;
}
private JTextArea getta() {
if (ta== null) {
ta= new JTextArea();
//ta.setText("ta");
}
return ta;
}
private JButton getbut() {
if (but == null) {
but = new JButton();
but.setText("遍历");
but.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
butActionActionPerformed(event);
}
});
}
return but;
}
private JTextField gettf() {
if (tf == null) {
tf = new JTextField();
//tf.setText("tf");
}
return tf;
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class.
* Note: This class is only created so that you can easily preview the result at runtime.
* It is not expected to be managed by the designer.
* You can modify it as you like.
*/
public static void main(String[] args) {
installLnF();
MU frame = new MU();
frame.setDefaultCloseOperation(MU.EXIT_ON_CLOSE);
frame.setTitle("MU");
frame.getContentPane().setPreferredSize(frame.getSize());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void butActionActionPerformed(ActionEvent e)
{
String dirPath = tf.getText();
System.out.println(dirPath);
File dir = new File(dirPath);
long start=System.currentTimeMillis();
ta.setText("请稍后。。。");
basic(dir);
long end=System.currentTimeMillis();
long time=end-start;
lb1.setText(time+"毫秒");
}
private void basic(File dir)
{
File[]files=dir.listFiles();
if(files!=null)
{
for(int i=0;i { ta.append(files[i].toString()+"\r\n"); System.out.println(files[i]); } } } } package No1; import java.awt.*; import java.awt.event.*; class APp { private Frame f; private MenuBar mb; private Menu m,subMenu; private MenuItem closeItem,subItem; APp() { init(); } public void init() { f = new Frame("my window"); f.setBounds(300,100,500,600); f.setLayout(new FlowLayout()); 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); } private void myEvent() { closeItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { new APp(); } } package days18; import java.awt.*; import java.awt.event.*; import java.io.*; public class MyMenuTest { private Frame f; private MenuBar bar; private TextArea ta; private Menu fileMenu; private MenuItem openItem,saveItem,closeItem; private FileDialog openDia,saveDia; private File file; MyMenuTest() { init(); } public void 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); } private void myEvent() { saveItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(file==null) { saveDia.setVisible(true); String dirPath = saveDia.getDirectory(); String fileName = saveDia.getFile(); if(dirPath==null || fileName==null) return ; file = new File(dirPath,fileName); } try { BufferedWriter bufw = new BufferedWriter(new FileWriter(file)); String text = ta.getText(); bufw.write(text); //bufw.flush(); bufw.close(); } catch (IOException ex) { throw new RuntimeException(); } } }); openItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openDia.setVisible(true); String dirPath = openDia.getDirectory(); String fileName = openDia.getFile(); // System.out.println(dirPath+"..."+fileName); if(dirPath==null || fileName==null) return ; ta.setText(""); file = new File(dirPath,fileName); try { BufferedReader bufr = new BufferedReader(new FileReader(file)); String line = null; while((line=bufr.readLine())!=null) { ta.append(line+"\r\n"); } bufr.close(); } catch (IOException ex) { throw new RuntimeException("读取失败"); } } }); closeItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { new MyMenuTest(); } } 划线示例代码: package days18; import java.awt.*; import java.awt.event.*; public class DrawLine { Frame f= new Frame("黑马"); public static void main(String [] args) { new DrawLine().init(); } public void init() { f.setSize(300,300); f.setVisible(true); f.addMouseListener(new MouseAdapter() { int orgX; int orgY; public void mousePressed(MouseEvent e) { orgX=e.getX(); orgY=e.getY(); } public void mouseReleased(MouseEvent e) { f.getGraphics().setColor(Color.red); //设置绘图颜色为红色 f.getGraphics().drawLine(orgX,orgY,e.getX(),e.getY()); } }); } } 显示图片代码 package days18; import java.awt.*; import java.awt.event.*; public class DrawImage extends Frame { Image img=null; public static void main(String [] args) { DrawImage f= new DrawImage(); f.init(); } public void init() { img=this.getToolkit().getImage("c:\\1.jpg"); setSize(300,300); setVisible(true); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public void paint(Graphics g) { getGraphics().drawImage(img,0,0,this); } } 划线强化代码 package days18; import java.awt.*; import java.awt.event.*; public class DrawLine extends Frame { Image oimg=null; Graphics og=null; public static void main(String [] args) { new DrawLine().init(); } public void init() { setSize(300,300); setVisible(true); Dimension d=getSize(); oimg=createImage(d.width,d.height); og=oimg.getGraphics(); addMouseListener(new MouseAdapter() { int orgX; int orgY; public void mousePressed(MouseEvent e) { orgX=e.getX(); orgY=e.getY(); } public void mouseReleased(MouseEvent e) { Graphics g=getGraphics(); g.setColor(Color.red);//设置绘图颜色为红色 g.setFont(new Font("隶书",Font.ITALIC|Font.BOLD,30)); //设置文本的字体 g.drawString(new String(orgX +"," +orgY),orgX,orgY); //打印鼠标按下时的坐标文本 g.drawString(new String(e.getX() +"," +e.getY()), e.getX(),e.getY());//打印鼠标释放时的坐标文本 g.drawLine(orgX,orgY,e.getX(),e.getY()); og.setColor(Color.red);//设置绘图颜色为红色 og.setFont(new Font("隶书",Font.ITALIC|Font.BOLD,30)); //设置文本的字体 og.drawString(new String(orgX +"," +orgY),orgX,orgY); //打印鼠标按下时的坐标文本 og.drawString(new String(e.getX() +"," +e.getY()), e.getX(),e.getY());//打印鼠标释放时的坐标文本 og.drawLine(orgX,orgY,e.getX(),e.getY()); } }); } public void paint(Graphics g) { if(oimg !=null) g.drawImage(oimg,0,0,this); } } 计时器代码 package days19; import java.awt.*; import java.awt.event.*; import java.util.*; import java.text.SimpleDateFormat; class StopWatch extends Canvas implements Runnable { private long startTime = 0; private long endTime = 0; private boolean bStart = false; public StopWatch() { enableEvents(AWTEvent.MOUSE_EVENT_MASK); setSize(80,30); } protected void processMouseEvent(MouseEvent e) { if(e.getID() == MouseEvent.MOUSE_PRESSED) { /*鼠标按下时,启动计时线程,并让起始时间变量和终止时间变量都等于当前时间*/ bStart = true; startTime = endTime = System.currentTimeMillis(); repaint(); new Thread(this).start(); } else if(e.getID() == MouseEvent.MOUSE_RELEASED) { /*鼠标释放时,终止计时线程,并重绘窗口表面上的内容*/ bStart = false; repaint(); } super.processMouseEvent(e); } public void paint(Graphics g) { /*时间值的小时、分钟、秒、都用两位数字显示, 不足两位的部分前面加0,即"HH:mm:ss"这种的格式。*/ SimpleDateFormat sdf= new SimpleDateFormat("HH:mm:ss"); /*最刚开始编写这个程序的时候,直接使用elapsedTime.setTime(endTime-startTime); 语句设置elapsedTime时间对象的数字值,从运行结果上发现,即使endTime-startTime等于0, 但elapsedTime显示的时间却不是"00:00:00",而是"08:00:00"。我们曾经讲过,时间在计算机 内存中也是用一个长整数表示的,在这里,我们又发现,即使这个内存中的长整数等于0时,由于 Date类考虑了本地时区问题,所以,其表示的时间就不一定为"零点:零分:零秒"。这里不需要 考虑时区问题,只是借助Date类来帮我们生成"HH:mm:ss"这种时间表示格式。明白这个问题后, 我们就不难想像出,可以先求出显示时间为"00:00:00"的时间对象在内存中对应的那个长整数, 然后在这个基础上加上计时器所记下的时间值,最后就可以显示出我们想要的结果。*/ Date elapsedTime =null; try { elapsedTime= sdf.parse("00:00:00"); }catch(Exception e){} elapsedTime.setTime(endTime - startTime + elapsedTime.getTime()); String display = sdf.format(elapsedTime); g.drawRect(0,0,78,28); g.fill3DRect(2,2,75,25,true); g.setColor(Color.WHITE); g.drawString(display,10,20); } public void run() { while(bStart) { try { Thread.sleep(500); }catch(Exception e){e.printStackTrace();} endTime = System.currentTimeMillis(); repaint(); } } } public class TestStopWatch { public static void main(String [] args) { Frame f =new Frame("StopWatch"); f.add(new StopWatch()); f.setSize(200,200); f.setVisible(true); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); } } 选择框代码 package days19; import java.awt.*; import java.awt.event.*; public class TestChoice { Choice ch=new Choice(); //创建Choice对象 TestChoice() { ch.add("choice1"); //用add方法向列表里加入选项 ch.add("choice2"); //用add方法向列表里加入选项 ch.add("choice3"); //用add方法向列表里加入选项 FlowLayout fl=new FlowLayout(); Frame f=new Frame("TestChoice"); f.setLayout(fl); f.add(ch); //把列表加入到窗口 f.setBounds(0,0,200,100); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { new TestChoice(); } } 菜单条代码 package days19; import java.awt.*; import java.awt.event.*; public class TestMenuBar { MenuBar menubar=new MenuBar(); //创建菜单条对象 Menu fileM=new Menu("File"); //创建各菜单 Menu editM=new Menu("Edit"); //创建各菜单 Menu toolsM=new Menu("Tools"); //创建各菜单 Menu helpM=new Menu("Help"); //创建各菜单 MenuItem fileMI1=new MenuItem("New"); //创建各菜单项 MenuItem fileMI2=new MenuItem("Open"); //创建各菜单项 MenuItem fileMI3=new MenuItem("Save"); //创建各菜单项 CheckboxMenuItem fileMI5=new CheckboxMenuItem("Quit",true); //创建各菜单项 Menu filePrint = new Menu("print");//创建子菜单 MenuItem printM1 = new MenuItem("preview"); MenuItem printM2 = new MenuItem("setting"); TestMenuBar() { FlowLayout fl=new FlowLayout(); Frame f=new Frame("TestMenuBar"); f.setLayout(fl); menubar.add(fileM); //将菜单加入菜单条 menubar.add(editM); menubar.add(toolsM); menubar.add(helpM); fileM.add(fileMI1); //将菜单项加入file菜单中 fileM.add(fileMI2); fileM.add(fileMI3); filePrint.add(printM1);//将菜单项加入print菜单中 filePrint.add(printM2); fileM.add(filePrint); //将print菜单作为一个菜单项加入file菜单中 fileM.addSeparator(); //将一条分割线加入菜单中 fileM.add(fileMI5); //将菜单项加入菜单中 f.setMenuBar(menubar); //把整个菜单系统显示在窗口中 f.setBounds(0,0,250,200); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { new TestMenuBar(); } } 对话框代码 package days19; import java.awt.*; import java.awt.event.*; public class TestDialog { TextField tf = new TextField(10); Button b1=new Button("模态显示"); Button b2=new Button("非模态显示"); Frame f=new Frame("TestDialog"); Button b3=new Button("确定"); Dialog dlg = new Dialog(f, "Dialog Title", true); FlowLayout fl=new FlowLayout(); TestDialog() { f.setLayout(fl); f.add(tf); f.add(b1); f.add(b2); b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { dlg.setModal(true); dlg.setVisible(true); tf.setText("www.it315.org"); } }); b2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { dlg.setModal(false); dlg.setVisible(true); tf.setText("www.it315.org"); } }); f.setBounds(0,0,400,200); f.setVisible(true); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); dlg.setLayout(fl); dlg.add(b3); b3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dlg.dispose(); } }); dlg.setBounds(0,0,200,150); } public static void main(String[] args) { new TestDialog(); } } 面板代码 package days19; import java.awt.*; import java.awt.event.*; public class TestPane { TestPane() { Frame f=new Frame("TestDialog"); ScrollPane sp = new ScrollPane(); TextArea ta = new TextArea("",10,50,TextArea.SCROLLBARS_NONE); sp.add(ta); f.add(sp); f.setSize(200,200); f.setVisible(true); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { new TestPane(); } } 卡片布局管理器代码 package days19; import java.awt.*; import java.awt.event.*; public class TestCardLayout { CardLayout cl = new CardLayout(); Panel plCenter = new Panel(); public static void main(String [] args) { new TestCardLayout().init(); } public void init() { Frame f=new Frame("布局管理器"); Panel plWest = new Panel(); f.add(plWest,"West"); f.add(plCenter); plWest.setLayout(new GridLayout(3,1)); Button btnPrev = new Button("prev"); plWest.add(btnPrev); Button btnNext = new Button("next"); plWest.add(btnNext); Button btnThree = new Button("three"); plWest.add(btnThree); plCenter.setLayout(cl); plCenter.add(new Button("One"),"1"); plCenter.add(new Button("two"),"2"); plCenter.add(new Button("three"),"3"); plCenter.add(new Button("four"),"4"); plCenter.add(new Button("five"),"5"); class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("prev")) cl.previous(plCenter); else if(e.getActionCommand().equals("next")) cl.next(plCenter); else if(e.getActionCommand().equals("three")) cl.show(plCenter,"3"); } } MyActionListener ma = new MyActionListener(); btnPrev.addActionListener(ma); btnNext.addActionListener(ma); btnThree.addActionListener(ma); f.setSize(300,300); f.setVisible(true); } } 计算器代码 package days19; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Calculator implements ActionListener { JFrame jf = new JFrame("Calculator"); JTextField tf = new JTextField(); public void init() { Container c = jf.getContentPane(); tf.setHorizontalAlignment(JTextField.RIGHT); c.add(tf,"North"); JPanel pnl=new JPanel(); c.add(pnl,"Center"); pnl.setLayout(new GridLayout(4,4)); JButton b=new JButton("1"); b.addActionListener(this); pnl.add(b); b=new JButton("2"); b.addActionListener(this); pnl.add(b); b=new JButton("3"); b.addActionListener(this); pnl.add(b); b=new JButton("+"); b.addActionListener(this); pnl.add(b); b=new JButton("4"); b.addActionListener(this); pnl.add(b); b=new JButton("5"); b.addActionListener(this); pnl.add(b); b=new JButton("6"); b.addActionListener(this); pnl.add(b); b=new JButton("-"); b.addActionListener(this); pnl.add(b); b=new JButton("7"); b.addActionListener(this); pnl.add(b); b=new JButton("8"); b.addActionListener(this); pnl.add(b); b=new JButton("9"); b.addActionListener(this); pnl.add(b); b=new JButton("*"); b.addActionListener(this); pnl.add(b); b=new JButton("0"); b.addActionListener(this); pnl.add(b); b=new JButton("."); b.addActionListener(this); pnl.add(b); b=new JButton("="); b.addActionListener(this); pnl.add(b); b=new JButton("\\"); b.addActionListener(this); pnl.add(b); jf.setSize(200,300); jf.setVisible(true); } public void actionPerformed(ActionEvent e) { tf.setText(tf.getText()+e.getActionCommand()); } public static void main(String [] args) { new Calculator().init(); } } 34、Applet 网页脚本编程原理 Applet由浏览器启动执行 1、浏览器载入HTML文件 2、浏览器载入HTML文件引用的Applet字节码 3、浏览器启动Java虚拟机执行Applet Applet小程序通常需要覆盖的方法 1、init()方法 2、Start()方法 3、Stop()方法 4、Destory()方法 5、Paint()方法 显示动画的Applet小程序 用于定时轮循显示一个数组中的10幅图像以产生动画效果,这个程序可以分为两个阶段来完成 1、实现定时功能,让一个index变量的取值,每隔100毫秒在1-30之间循环变量表示 2、增加显示图像动画的功能,只要在每次改变index变量的值后,显示出数组中的第index个图像就可以产生动画效果 import java.applet.*; import java.awt.*; import java.net.*; public class Ima extends Applet implements Runnable { String str; int x=0; public void init() { new Thread(this).start(); } public void paint(Graphics g) { str=Integer.toString(x); x++; g.setColor(Color.BLUE); g.setFont(new Font("隶书",Font.BOLD,30)); g.drawString(str, 30, 40); } public void run() { while(x<30) { try { repaint(); Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[]args) { new Ima(); } } 带显示图片的案例代码 import java.applet.*; import java.awt.*; import java.net.*; public class MyApplet extends Applet implements Runnable { Image [] imgs=new Image[10]; int index=0; public void init() { try{ for(int i=0;i<10;i++) { imgs[i]=getImage(new URL(getCodeBase(),"img\\T" + (i+1) +".gif")); /*imgs[i]=getToolkit().getImage(new URL(getCodeBase(), "img\\T" +(i+1) +".gif"));*/ } new Thread(this).start(); } catch(Exception e){e.printStackTrace();} } public void paint(Graphics g) { g.drawImage(imgs[index],0,0,this); /*下面设置的字体必须是你的计算机中存在的字符,打开记事本程序的字体设置对话框, 从其中可选的字体中复制一个到这里就行了。*/ g.setFont(new Font("隶书",Font.ITALIC|Font.BOLD,30)); index=(index+1)%10; g.drawString("" + index,0,50); } public void run() { while(true) { repaint(); try { Thread.sleep(100); }catch(Exception e){} } } } Applet相关知识 Aplplet的局限性 1、不能启动执行其他应用程序 2、不能进行文件I/O操作 3、不能调用本机代码 4、不能与Applet所在的主机之外的其他主机进行网络连接 1、w3c协会建议人们用标记来代替标记 2、使用HTML Converter将标记转换成标记 3、使用标记,执行Applet小程序的java解释器被作为一个ActiveX插件使用 4、使用标记比标记多了自动加载和安装Java解释器(一个插件)的功能 在多个网页中引用同一个Applet类 问题:如果两个网页中都用到同一个Applet类,当浏览器访问了第一个网页后,接着再去访问第二个网页时,是否为第二个网页创建一个新的Applet对象呢?或者还是使用第一个网页中创建的Applet对象呢 解答:使用一个静态或者变量来统计创建的Applet实例对象个数,从而发现如何产生和调用Applet的实例对象,完全有嵌入到浏览器的java解释器控制,不同厂家的Java解释器甚至同一个人厂子的不同版本,java解释器都不一样