Hello World Swing java import javax swing import

  • Slides: 94
Download presentation

示例(Hello. World. Swing. java) import javax. swing. *; import java. awt. event. *; public

示例(Hello. World. Swing. java) import javax. swing. *; import java. awt. event. *; public class Hello. World. Swing { public static void main(String[] args) { JFrame frame = new JFrame("Hello. World. Swing"); final JLabel label = new JLabel("Hello World!"); frame. get. Content. Pane(). add(label); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); frame. set. Size(200, 70); frame. set. Visible(true); } }

import相关的包 l GUI相关的类主要包含在以下包中: • import java. awt. *; • import javax. swing. *; •

import相关的包 l GUI相关的类主要包含在以下包中: • import java. awt. *; • import javax. swing. *; • import java. awt. event. *;

选择GUI外观风格L&F(不是必须的) l 使用UIManager. set. Look. And. Feel()进行设置 参数 L&F UIManager. get. Cross. Platform. Look.

选择GUI外观风格L&F(不是必须的) l 使用UIManager. set. Look. And. Feel()进行设置 参数 L&F UIManager. get. Cross. Platform. Look. And. Feel. Class. Name() 跨平台的Java L&F UIManager. get. System. Look. And. Feel. Class. Name() 当前运行平台的L&F “com. sun. java. swing. plaf. windows. Windows. Look. And. Feel” Windows L&F l L&F设置应是main方法要执行的第一个操作

JFrame l 最常用的顶层容器,一般作为应用程序主窗口 l 构造方法 • JFrame(); • JFrame(String title); l 显示初始创建的JFrame • set.

JFrame l 最常用的顶层容器,一般作为应用程序主窗口 l 构造方法 • JFrame(); • JFrame(String title); l 显示初始创建的JFrame • set. Visible(true); l 设置单击关闭窗口按钮操作 • public void set. Default. Close. Operation(int op); op 含义 Window. Constants. DO_NOTHING_ON_CLOSE 不做任何动作 Window. Constants. HIDE_ON_CLOSE 隐藏窗口 Window. Constants. DISPOSE_ON_CLOSE 关闭窗口,释放资源 JFrame. EXIT_ON_CLOSE 退出应用系统

对JFrame添加组件的两种方式 l 用get. Content. Pane()方法获得JFrame的内容面板, 再用add()方法向其中加入组件 frame. get. Content. Pane(). add(new JLabel(“Hello”)); l 建立一个中间容器(JPanel或JDesktop.

对JFrame添加组件的两种方式 l 用get. Content. Pane()方法获得JFrame的内容面板, 再用add()方法向其中加入组件 frame. get. Content. Pane(). add(new JLabel(“Hello”)); l 建立一个中间容器(JPanel或JDesktop. Pane), 将组件添加到中间容器中,再用set. Content. Pane() 方法将该容器设置为JFrame的内容面板 JPanel content. Pane = new JPanel(); JButton b =new JButton(“确定”); content. Pane. add(b); … frame. set. Content. Pane(content. Pane);

/*创建一个带有空JLabel的JFrame*/ public class JFrame. Demo { public static void main(String s[]) { // 指定使用当前的Look&Feel装饰窗口,必须在创建窗口前设定

/*创建一个带有空JLabel的JFrame*/ public class JFrame. Demo { public static void main(String s[]) { // 指定使用当前的Look&Feel装饰窗口,必须在创建窗口前设定 JFrame. set. Default. Look. And. Feel. Decorated(true); // 创建并设定关闭窗口操作 JFrame frame = new JFrame("JFrame. Demo"); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); // 创建一个JLable并加到窗口中 JLabel empty. Label = new JLabel(""); empty. Label. set. Preferred. Size(new Dimension(175, 100)); frame. get. Content. Pane(). add(empty. Label, Border. Layout. CENTER); // 显示窗口 frame. pack(); frame. set. Visible(true); } }

public class Frame. With. Panel extends JFrame { public static void main(String args[]) {

public class Frame. With. Panel extends JFrame { public static void main(String args[]) { Frame. With. Panel fr = new Frame. With. Panel("Hello !"); fr. set. Size(200, 200); fr. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); JPanel pan = new JPanel(); /* 创建JPanel的实例 */ pan. set. Background(Color. yellow); pan. set. Layout(new Grid. Layout(2, 1)); pan. add(new JButton("确定")); fr. set. Content. Pane(pan); fr. set. Visible(true); } public Frame. With. Panel(String str) { super(str); } }

/* Flow. Layout示例 */ public class Flow. Layout. Window extends JFrame { public Flow.

/* Flow. Layout示例 */ public class Flow. Layout. Window extends JFrame { public Flow. Layout. Window() { set. Layout(new Flow. Layout()); add(new JLabel("Buttons: ")); add(new JButton("Button 1")); add(new JButton("2")); add(new JButton("Button 3")); add(new JButton("Long-Named Button 4")); add(new JButton("Button 5")); } public static void main(String args[]) { Flow. Layout. Window window = new Flow. Layout. Window(); window. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); window. set. Title("Flow. Layout. Window Application"); window. pack(); // 窗口大小设置为适合组件最佳尺寸与布局所需的空间 window. set. Visible(true); } }

Border. Layout l JFrame, JDialog和JWindow的默认布局管理器 l 将容器分为 5个区:East,West,South,North, Center l 当用户改变容器窗口大小时,各组件的相对位置 不变,但组件的大小改变 North West

Border. Layout l JFrame, JDialog和JWindow的默认布局管理器 l 将容器分为 5个区:East,West,South,North, Center l 当用户改变容器窗口大小时,各组件的相对位置 不变,但组件的大小改变 North West Center East South

Border. Layout l 构造方法 • Border. Layout():组件间没有水平和垂直间隙 • Border. Layout(int hgap, int vgap):指定组件间的水平 间隙(hgap)和垂直间隙(vgap)

Border. Layout l 构造方法 • Border. Layout():组件间没有水平和垂直间隙 • Border. Layout(int hgap, int vgap):指定组件间的水平 间隙(hgap)和垂直间隙(vgap) l 向容器中加入组件时,要指定摆放的位置,否则 组件将不能显示。两个add方法: • Public Component add(Component comp, String name) • Public void add(Component comp, Object constraints) • 例:Border. Layout. Window. java

Card. Layout l 常用方法 • public void add. Layout. Component(Component comp, Object constraints):将指定组件comp加入Card. Layout,

Card. Layout l 常用方法 • public void add. Layout. Component(Component comp, Object constraints):将指定组件comp加入Card. Layout, 并将其与constraints所指定的名称字符串相关联 • public void first (Container parent):显示第一张卡片 • public void next (Container parent):显示下一张卡片( 如果当前是最后一张,则显示第一张) • public void previous(Container parent):显示前一张卡 片 • public void last (Container parent):显示最后一张卡片 • public void show (Container parent, String name):显 示指定名称的组件 • 例:Card. Layout. Window. java

委托模型(delegation model) l 定义监听器类 • 声明监听器类 public class My. Class implements Action. Listener{ …

委托模型(delegation model) l 定义监听器类 • 声明监听器类 public class My. Class implements Action. Listener{ … } üMy. Class将成为处理Action. Event事件的监听器类, 它的对象可作为Button等组件的事件监听器 • 实现监听器接口,即在监听器类中实现监听器接口中 所有的方法 public class My. Class implements Action. Listener{ public void action. Performed(Action. Event e){ … //响应某个动作的代码 } }

委托模型(delegation model) l 注册监听器 • 通过调用组件的add. XXXListener()方法,在组件上将 监听器类的实例注册为监听器,如 some. Component. add. XXXListener(new Myclass());

委托模型(delegation model) l 注册监听器 • 通过调用组件的add. XXXListener()方法,在组件上将 监听器类的实例注册为监听器,如 some. Component. add. XXXListener(new Myclass());

委托模型(delegation model) Action. Event事件 Action. Listener接口 public void action. Performed(Action. Event e) �� 接口

委托模型(delegation model) Action. Event事件 Action. Listener接口 public void action. Performed(Action. Event e) �� 接口 � 听器� � 例化 � 听器 Button. add. Action. Listener( ) �象 �� 按扭指定� 听器

/* 委托式的事件处理机制的实现实例(单击按钮事件响应) */ public class Test. Button { public static void main(String args[]) {

/* 委托式的事件处理机制的实现实例(单击按钮事件响应) */ public class Test. Button { public static void main(String args[]) { JFrame f = new JFrame("Test"); f. set. Size(200, 100); f. set. Layout(new Flow. Layout(Flow. Layout. CENTER)); f. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); JButton b = new JButton("Press Me!"); b. add. Action. Listener(new Button. Handler()); // 注册点击鼠标事件监听器 f. add(b); f. set. Visible(true); } } // 定义Action. Event监听器类 class Button. Handler implements Action. Listener { public void action. Performed(Action. Event e) { System. out. println("Action occurred"); System. out. println("Button's label is: " + e. get. Action. Command()); } }

监听器接口及其方法(部分) Event类型 Window 接口名 Window. Listener 适配器名 Window. Adapter 方法 void window. Closing (Window.

监听器接口及其方法(部分) Event类型 Window 接口名 Window. Listener 适配器名 Window. Adapter 方法 void window. Closing (Window. Event e) void window. Opening (Window. Event e) void window. Activated (Window. Event e) void window. Deactivated (Window. Event e) void window. Closed (Window. Event e) void window. Iconified (Window. Event e) void window. Deiconified (Window. Event e) Action. Listener void action. Performed (Action. Event e ) Item. Listener void item. State. Changed (Item. Event e) Mouse. Motion. Listener Mouse. Motion. Adapter void mouse. Dragged (Mouse. Event e) Motion void mouse. Moved (Mouse. Event e) Mouse. Listener Mouse. Adapter void mouse. Pressed (Mouse. Event e) Button void mouse. Released (Mouse. Event e) void mouse. Entered (Mouse. Event e) void mouse. Exited (Mouse. Event e) void mouse. Clicked (Mouse. Event e) Key. Listener Key. Adapter void key. Pressed (Key. Event e) void key. Released (Key. Event e) void key. Typed (Key. Event e) Focus. Listener Focus. Adapter void focus. Gained (Focus. Event e) void focus. Lost (Focus. Event e) Component. Listener Component Adapter void component. Moved (Component. Event e) void component. Resized (Component. Event e) void component. Hidden (Component. Event e) void component. Shown (Component. Event e)

JComponent组件 l Swing组件中,除了顶层容器组件,所有以J 开头的组件都是JComponent类的子类 l JComponent是java. awt. Container类的子类

JComponent组件 l Swing组件中,除了顶层容器组件,所有以J 开头的组件都是JComponent类的子类 l JComponent是java. awt. Container类的子类

Show. Message. Dialog l 显示一段提示性信息 //带有信息图标,标题为“消息”的对话框 JOption. Pane. show. Message. Dialog(this, “Eggs aren’t supposed

Show. Message. Dialog l 显示一段提示性信息 //带有信息图标,标题为“消息”的对话框 JOption. Pane. show. Message. Dialog(this, “Eggs aren’t supposed to be green. ”) //带有警告图标的对话框 JOption. Pane. show. Message. Dialog(this, “Eggs aren’t supposed to be green. ”, Warning, JOption. Pane. WARNING_MESSAGE) • 例:Test. JOption. Pane. java的Listener 1

show. Option. Dialog l 选项对话框的返回值是用户所单击的按钮在 Options数组中的序号 //定义按钮上的文本 Object[] options={“Yes, please”, “No thanks”, “No eggs,

show. Option. Dialog l 选项对话框的返回值是用户所单击的按钮在 Options数组中的序号 //定义按钮上的文本 Object[] options={“Yes, please”, “No thanks”, “No eggs, no ham!”} int n=JOption. Pane. show. Option. Dialog (frame, “Would you like some green eggs to go”+ “with that ham? ”, “A Silly Question”, JOption. Pane. YES_NO_CANCEL_OPTION, JOption. Pane. QUESTION_MESSAGE, null, options, options[2]); • 例:Test. JOption. Pane. java的Listener 2

show. Input. Dialog l show. Input. Dialog()方法有多种格式,它们都是保 留message参数而省略了其他不同参数而构成的 • Object[] possible. Value={“First”, “Second”, “Third”};

show. Input. Dialog l show. Input. Dialog()方法有多种格式,它们都是保 留message参数而省略了其他不同参数而构成的 • Object[] possible. Value={“First”, “Second”, “Third”}; Object selected. Value = JOption. Pane. show. Input. Dialog (null, “ Choose one”, “Input”, JOption. Pane. INFORMATION_MESSAGE, null, possible. Vaule[0]); • String input. Value = JOption. Pane. show. Input. Dialog(“Please input a value”); • 例:Test. JOption. Pane. java的Listener 3

show. Confirm. Dialog l 用来显示一个确认对话框 • JOption. Pane. show. Confirm. Dialog (null, “choose one”,

show. Confirm. Dialog l 用来显示一个确认对话框 • JOption. Pane. show. Confirm. Dialog (null, “choose one”, JOption. Pane. YES_NO_OPTION); • 例:Test. JOption. Pane. java的Listener 4 l 更多例子:Example. Swing/Dialog. Demo. java

JScroll. Pane l 构造方法 • Public JScroll. Pane(Component view, int vsb. Policy, int hsb.

JScroll. Pane l 构造方法 • Public JScroll. Pane(Component view, int vsb. Policy, int hsb. Policy) üview:客户组件 üvsb. Policy和hsb. Policy:垂直和水平滚动条的显示策 略,从以下值中选取: – JScroll. Pane. VERTICAL_SCROLLBAR_AS_NEEDED – JScroll. Pane. VERTICAL_SCROLLBAR_NEVER – JScroll. Pane. VERTICAL_SCROLLBAR_ALWAYS • 例:Test. JScroll. Pane. java

JSplit. Pane l 可显示(水平或垂直摆放的)两个组件 l 可通过操作JSplit. Pane中间的分隔条,调整两个组 件所占空间的大小 l 构造方法 • JSplit. Pane(int new.

JSplit. Pane l 可显示(水平或垂直摆放的)两个组件 l 可通过操作JSplit. Pane中间的分隔条,调整两个组 件所占空间的大小 l 构造方法 • JSplit. Pane(int new. Orientation, Component new. Left. Component, Component new. Right. Component) ünew. Orientation:分割的方向,可选值: – JSplit. Pane. HORIZONTAL_SPLIT – JSplit. Pane. VERTICAL_SPLIT ünew. Left. Component:位于JSplit. Pane左边或上边区 域的组件 ünew. Right. Ccomponent:位于JSplit. Pane右边或下边 区域的组件

JSplit. Pane l 创建带有两个滚动面板的分割面板 • split. Pane=new JSplit. Pane(JSplit. Pane. HORIZONTAL_SPLIT, list. Scroll. Pane,

JSplit. Pane l 创建带有两个滚动面板的分割面板 • split. Pane=new JSplit. Pane(JSplit. Pane. HORIZONTAL_SPLIT, list. Scroll. Pane, picture. Scroll. Pane); l 设置每个分面板的快速扩展按钮 • split. Pane. set. One. Touch. Expandable(true); l 设置分隔条的位置 • split. Pane. set. Divider. Location(150); l 指定滚动面板中两个组件的最小尺寸 • Dimension minimum. Size =new Dimension(100, 50); • list. Scroll. Pane. set. Minimum. Size(minimum. Size); • picture. Scroll. Pane. set. Minimum. Size(minimum. Size); • Example. Swing/Split. Pane. Demo. java

JTabbed. Pane l 构造方法 • JTabbed. Pane(); • JTabbed. Pane(int tab. Placement, int tab.

JTabbed. Pane l 构造方法 • JTabbed. Pane(); • JTabbed. Pane(int tab. Placement, int tab. Layout. Policy); ütab. Placement:组件标签的位置,可取值: – – JTabbed. Pane. TOP(默认) JTabbed. Pane. BOTTOM JTabbed. Pane. LEFT JTabbed. Pane. RIGHT ütab. Layout. Policy:标签的布局策略。当多个标签充 满JTabbed. Pane窗口时,采用此策略。可取值: – WRAP_TAB_LAYOUT – SCROLL_TAB_LAYOUT

JTabbed. Pane l 向JTabbed. Pane中添加带有标签的组件 • void add. Tab(String title, Icon icon, Component component,

JTabbed. Pane l 向JTabbed. Pane中添加带有标签的组件 • void add. Tab(String title, Icon icon, Component component, String tip) • void add. Tab(String title, Icon icon, Component component) • void add. Tab(String title, Component component) ütitle:标签上的文字 üicon:标签上的图标 ücomponent:选择该标签时要显示的组件 ütip:标签的提示信息 • 例:Example. Swing/Tabbed. Pane. Demo. java

JTool. Bar l 创建 具条 JTool. Bar tool. Bar = new JTool. Bar(); l

JTool. Bar l 创建 具条 JTool. Bar tool. Bar = new JTool. Bar(); l 创建并添加第一个按钮 JButton button=new JButton(new Image. Icon(“left. gif”)); button. set. Tool. Tip. Text(“This is the left button”); button. add. Action. Listener(new Action. Listener(){ public void action. Performed(Action. Even e){ display. Result(“Action for first button”); } } ); tool. Bar. add(button); • 例:Example. Swing/Tool. Bar. Demo. java

JButton的使用 Image. Icon left. Button. Icon = new Image. Icon(“right. gif”); … //创建左边的按钮 b

JButton的使用 Image. Icon left. Button. Icon = new Image. Icon(“right. gif”); … //创建左边的按钮 b 1= new JButton(“Disable middle button”, left. Button. Icon); b 1. set. Vertical. Text. Position(Abstract. Button. CENTER); b 1. set. Horizontal. Text. Position(Abstract. Button. LEADING) ; b 1. set. Mnemonic(Key. Event. VK_D); b 1. set. Action. Command(“disable”); 例:Example. Swing/Button. Demo. java 80

JCheck. Box(复选框)的使用 chin. Button=new JCheck. Box(“Chin”); chin. Button. set. Mnemonic(key. Event. VK_C); chin. Button.

JCheck. Box(复选框)的使用 chin. Button=new JCheck. Box(“Chin”); chin. Button. set. Mnemonic(key. Event. VK_C); chin. Button. set. Selected(true); … glass. Button=new JCheck. Box(“Glasses”); glass. Button. set. Mnemonic(key. Event. VK_G); glass. Button. set. Selected(true); … 例:Example. Swing/Check. Box. Demo. java 81

JRadio. Button的使用 JRadio. Button bird. Button =new JRadio. Button(birdstring); bird. Button. set. Mnemonic(Key. Event.

JRadio. Button的使用 JRadio. Button bird. Button =new JRadio. Button(birdstring); bird. Button. set. Mnemonic(Key. Event. VK_B); bird. Button. set. Action. Command(birdstring); bird. Button. set. Selected(true); … //将按钮组成单选按钮 Button. Group group=new Button. Group(); group. add(bird. Button); //注册单选按钮的事件监听器 bird. Button. add. Action. Listener(this); … 例:Example. Swing/Radio. Button. Demo. java 82

文本类组件 l Swing提供了5个文本组件 • • • JText. Field JPassword. Field JText. Area JEditor. Pane

文本类组件 l Swing提供了5个文本组件 • • • JText. Field JPassword. Field JText. Area JEditor. Pane JText. Pane 83

文本类组件 JText. Field final String text. Field. String=“JText. Field”; JText. Field text. Field=new JText.

文本类组件 JText. Field final String text. Field. String=“JText. Field”; JText. Field text. Field=new JText. Field(10); text. Field. set. Action. Command(text. Field. String); text. Field. add. Action. Listener(this); JPassword. Field final String password. Field. String=“JPassword. Field”; JPassword. Field password. Field=new Jpassword. Field(10); password. Field. set. Action. Command(password. Field. String); password. Field. add. Action. Listener(this); 84

文本类组件 JText. Area text. Area=new JText. Area(“This is an editable JText. Area”+“that has been

文本类组件 JText. Area text. Area=new JText. Area(“This is an editable JText. Area”+“that has been initialized with the set. Text method. ”+… ); text. Area. set. Font(new Font(“Serif”, Font. ITALIC, 16)); //自动换行 text. Area. set. Line. Wrap(true); //换行以单词为边界而不是以字母为边界 text. Area. set. Wrap. Style. Word(true); … 85

文本类组件 JEditor. Pane editor. Pane=new JEditor. Pane(); editor. Pane. set. Editable(false); … try{ editor.

文本类组件 JEditor. Pane editor. Pane=new JEditor. Pane(); editor. Pane. set. Editable(false); … try{ editor. Pane. set. Page(url); } catch(IOException e) { System. err. println(“Attempted to read a bad URL”+url); } • 例:Example. Swing/Text. Sampler. Demo. java 86

文本类组件 l JText. Pane:可以显示和编辑各种字体的文件,包括图标 和组件 JText. Pane text. Pane=new JText. Pane(); //定义Text Panel中显示的文本 String

文本类组件 l JText. Pane:可以显示和编辑各种字体的文件,包括图标 和组件 JText. Pane text. Pane=new JText. Pane(); //定义Text Panel中显示的文本 String init. String=“This is an editable JText. Pane. ” //创建Text Panel的数据模型 Document doc=text. Pane. get. Document(); //将init. String中定义的字符串在Text Panel中显示 Try{ doc. insert. String(doc. get. Length(), init. String, null); }catch(Bad. Location. Exception ble){ System. err. println(“Couldn’t insert initial text. ”); } • 例:Example. Swing/Text. Pane. Demo. java 87

标签JLabel l JLabel类的功能与AWT中的Label类似 l 区别 • JLabel中可以提供带图标的标签 • 图标和文字的相对位置可在创建标签时通过 Set. Vertical. Text. Position()和set. Horizontal.

标签JLabel l JLabel类的功能与AWT中的Label类似 l 区别 • JLabel中可以提供带图标的标签 • 图标和文字的相对位置可在创建标签时通过 Set. Vertical. Text. Position()和set. Horizontal. Text. Position() 进行设置 • 例:Example. Swing/Label. Demo. java 88

列表JList //创建并设置列表数据模型 list. Model=new Default. List. Model(); list. Model. add. Element(“Rabbit”) ; list. Model.

列表JList //创建并设置列表数据模型 list. Model=new Default. List. Model(); list. Model. add. Element(“Rabbit”) ; list. Model. add. Element(“Bird”) ; … //创建列表并放入滚动面板 list=new JList(list. Model); … • 例:Example. Swing/List. Dialog. java 89

表格JTable l JTable组件可以将数据以二维表的形式显示,并 可以经过设置允许用户对数据进行编辑 l 构造方法 • public JTable(Table. Model dm); • public JTable(Object[][]

表格JTable l JTable组件可以将数据以二维表的形式显示,并 可以经过设置允许用户对数据进行编辑 l 构造方法 • public JTable(Table. Model dm); • public JTable(Object[][] row. Data, Object[] column. Names); • public JTable(Vector row. Data, Vector column. Names); l 设置方法 • void set. Prefered. Scrollable. Viewport. Size(Dimension size); • 例:Example. Swing/Table. Demo. java 90

选择框JCombo. Box l 默认的不可编辑形式 • 例:Example. Swing/Combo. Box. Demo. java l 可编辑的选择框 • 例:Example.

选择框JCombo. Box l 默认的不可编辑形式 • 例:Example. Swing/Combo. Box. Demo. java l 可编辑的选择框 • 例:Example. Swing/Combo. Box. Demo 2. java 92

其他组件 l 颜色选择器JColor. Chooser • 例:Example. Swing/Color. Chooser. Demo. java l 进程条JProgress. Bar •

其他组件 l 颜色选择器JColor. Chooser • 例:Example. Swing/Color. Chooser. Demo. java l 进程条JProgress. Bar • 例:Example. Swing/Progress. Bar. Demo. java • 例:Example. Swing/Progress. Monitor. Demo. java l 滑动块Jslider • 例:Example. Swing/Slider. Demo. java l 微调器JSpinner 94