项目 |
内容 |
这个作业属于哪个课程 |
https://www.cnblogs.com/nwnu-daizh/ |
这个作业的要求在哪里 |
https://www.cnblogs.com/zyja/p/12000169.html |
作业学习目标 |
(1) 掌握菜单组件用途及常用API; (2) 掌握对话框组件用途及常用API; (3) 学习设计简单应用程序的GUI。 |
第一部分:总结菜单、对话框两类组件用途及常用API
一. 菜单
1. 菜单是GUI编程中经常用到的一种组件。 位于窗口顶部的菜单栏中包括下拉菜单的名字。 点击一个名字就可以打开包含菜单项和子菜单的菜单。
2. 创建一个菜单栏:菜单栏是一个可以添加到容器组件的任何位置的组件。 通常放置在框架的顶部。
JMenuBar menuBar=new JMenuBar();
3. 调用框架的setJMenuBar 方法可将一个菜单栏对象添加到框架上。 frame.serJMenuBar(menuBar);
4. 创建菜单对象,并将菜单对象添加到菜单栏中
JMenu editMenu = new JMenu("Edit");
menuBar.add(editMenu);
5. 向菜单对象添加一个菜单项
JMenuItem pasteitem = new JMenuItem();
editMenu.add(pasteitem);
6. 向菜单添加分隔符行
editMenu.addSeperator();
7. 向菜单对象项添加子菜单
JMenu optionsMenu = new Jmenu("option");
editMenu.add(optionsMenu);
8. 当用户选择菜单时,将触发一个动作事件。 这里需要为每一个菜单项安装一个动作监听器。
ActionListener listener=...;
pasteitem.addActionListener(listener);
9. 菜单对象的add方法可返回创建的子菜单项。 可以使用以下方法来获取他,并添加监听器:
JMenuItem pasteitem = editMenu.add("Paste");
pasteitem.addActionListener(listener);
二. 弹出菜单(JPopupMenu)
1. 弹出菜单是不固定在菜单栏中随处浮动的菜单
2. 创建一个弹出菜单与创建一个常规菜单的方法类似,但是弹出菜单没有标题:
JPopupMenu popup = new JPopupMenu();
3. 然后用常规方法为弹出菜单添加菜单项:
JMenuItem item = new JMenuItem("Cut");
item.addActionListener(listener);
popup.add(item);
4. 弹出菜单调用show方法才能显示出来:
popup.show(panel,x,y);
5. 弹出式触发器(pop-up trigger): • 用户点击鼠标某个键时弹出菜单
• 在Windows或者Linux中,弹出式触发器是鼠标右键
• 要想在用户点击某一个组件的时候弹出菜单,该组件就要调用以下方法设置弹出式触发器: component.setComponentPopupMenu(popup);
三. 快捷键
1. 可以为菜单项设置快捷键,在当前菜单打开的情况下,可按下某菜单的快捷键,相当于鼠标点击了该菜单项。
JMenuItem CutItem = new JMenuItem("Index");
CutItem.setMnemonic("I");
此快捷键就会自动显示在菜单项中,快捷键下面有一条下划线。
四. 加速器
1. 加速器可以在不打开菜单的情况下选中菜单项的快捷键,例如: CTRL+S关联到Save
2. 使用SetAccelerator方法可以将加速器关联到一个菜单项,该方法使用KeyStroke类型的对象做为参数
openitem.setAccelerator(KeyStroke.getKeyStroke("ctrl o"));
3. 加速器只关联在菜单项,而不能关联菜单。
4. 加速器实际上并不打开菜单,而是直接激活菜单关联的动作事件。
五. 启用和禁用菜单项
1. 屏蔽 / 启用菜单项的方法: aMenuItem.setEnabled(boolean)
2. 如果需要动态启用/ 屏蔽某菜单项,则需要为菜单项注册 "menuSelected" 事件监听器。javax.swing.event包定义了MenuListener接口它有三个方法
• void menuSelected(MenuEvent event)
• void menuDeselected(MenuEvent event)
• void menuCanceled(MenuEvent event)
五. 工具栏(JToolBar)
1. 调用setToolTest方法添加工具提示到 JComponent: exitButton.setToolTipText("Exit");
2. 如果使用Action对象 就可以用SHORT-DESCRIPTION关联工具提示:
exitButton.putValue(Action.SHORT-DESCRIPTION, "Exit");
六. 对话框
1. 它是一种大小不能变化,不能有菜单的容器窗口。
2. 对话框依赖于框架。当框架被清除时,对话框也会被清除。对话框在显示时,如果框架被最小化,对话框也将变为不可见。
3. 构造一个标题为" Dialog" 的模式对话框,该对话框为框架 frame所拥有 JDialog dialog = new JDialog(frame, "Dialog", true)
4. 选择对话框 (JOption Pane)
定义多个showXxxDialog形式的静态方法
• showMessageDialog--------信息对话框,显示信息,告知用户发生了什么
• showConfirmDialog ---------确认对话框,显示问题,要求用户进行确认
• showOptionDialog ----------选择对话框,显示选项,要求用户进行选择
• showInputDialog ------------输入对话框,提示用户进行输入
5. 创建对话框
• JDialog (Frame owner) ---------构造一个没有标提的非模式对话框
• JDialog (Frame owner, boolean modal) ------构造一个没有标题对话框,boolean型参数modal指定对话框是否为模式窗口
• JDialog(Frame owner, String title) -------构造一个有标题的非模式对话框
• JDialog (Frame owner, String title, boolean modal) -----构造一个有标题的对话框
6. showXxxDialog 方法的参数
• Component parentComponent 对话框的父窗口对象,其屏幕坐标将决定对话框的显示位置,此参数也可以为null, 表示采用缺省的Frame作为父窗口,此时对话框将设置在屏幕的正中
• Object message 显示对话框中的描述信息。 该参数是一个string对象,但也可以是一个图标,一个组件或者一个对象数组
2、实验内容和步骤
实验1:
测试程序1:
掌握菜单的创建、菜单事件监听器、复选框和单选按钮菜单项、弹出菜单以及快捷键和加速器的用法。
1 import java.awt.event.*; 2 import javax.swing.*; 3 4 /** 5 * A frame with a sample menu bar. 6 */ 7 public class MenuFrame extends JFrame 8 { 9 private static final int DEFAULT_WIDTH = 300; 10 private static final int DEFAULT_HEIGHT = 200; 11 private Action saveAction; 12 private Action saveAsAction; 13 private JCheckBoxMenuItem readonlyItem; 14 private JPopupMenu popup; 15 16 /** 17 * A sample action that prints the action name to System.out. 18 */ 19 class TestAction extends AbstractAction 20 { 21 public TestAction(String name) 22 { 23 super(name); 24 } 25 26 public void actionPerformed(ActionEvent event) 27 { 28 System.out.println(getValue(Action.NAME) + " selected."); 29 } 30 } 31 32 public MenuFrame() 33 { 34 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);//设置菜单框架的大小 35 36 JMenu fileMenu = new JMenu("File"); 37 fileMenu.add(new TestAction("New")); 38 39 // 演示加速器 40 41 JMenuItem openItem = fileMenu.add(new TestAction("Open")); // 42 openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O")); //将加速器ctrl O关联到openItem菜单项 43 44 fileMenu.addSeparator(); //在fileMenu菜单中添加分隔符 45 46 saveAction = new TestAction("Save"); 47 JMenuItem saveItem = fileMenu.add(saveAction); 48 saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S")); //将加速器ctrl S关联到saveItem菜单项 49 50 saveAsAction = new TestAction("Save As"); 51 fileMenu.add(saveAsAction); 52 fileMenu.addSeparator(); 53 54 fileMenu.add(new AbstractAction("Exit") 55 { 56 public void actionPerformed(ActionEvent event) 57 { 58 System.exit(0); 59 } 60 }); 61 62 // 演示复选框和单选按钮菜单 63 64 readonlyItem = new JCheckBoxMenuItem("Read-only"); //用Read-only构造一个复选框菜单项 65 readonlyItem.addActionListener(new ActionListener() 66 { 67 public void actionPerformed(ActionEvent event) 68 { 69 boolean saveOk = !readonlyItem.isSelected(); //获取菜单项的选择状态 70 saveAction.setEnabled(saveOk); //启用菜单项 71 saveAsAction.setEnabled(saveOk); 72 } 73 }); 74 75 ButtonGroup group = new ButtonGroup(); //为单选钮组构造一个对象 76 77 JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert");//创建一个单选按钮 78 insertItem.setSelected(true); //设置这个菜单的选择状态 79 JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype"); 80 81 group.add(insertItem);//把insertItem对象加到按钮组中 82 group.add(overtypeItem); 83 84 // 演示图标 85 86 TestAction cutAction = new TestAction("Cut"); 87 cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif")); 88 TestAction copyAction = new TestAction("Copy"); 89 copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif")); 90 TestAction pasteAction = new TestAction("Paste"); 91 pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif")); 92 93 JMenu editMenu = new JMenu("Edit"); 94 editMenu.add(cutAction); 95 editMenu.add(copyAction); 96 editMenu.add(pasteAction); 97 98 // 演示嵌套菜单 99 100 JMenu optionMenu = new JMenu("Options"); 101 102 optionMenu.add(readonlyItem); 103 optionMenu.addSeparator(); 104 optionMenu.add(insertItem); 105 optionMenu.add(overtypeItem); 106 107 editMenu.addSeparator(); 108 editMenu.add(optionMenu);//把optionMenu菜单嵌套在edit菜单中 109 110 // 演示助记符 111 112 JMenu helpMenu = new JMenu("Help"); 113 helpMenu.setMnemonic('H'); //为Help这个菜单设置快捷键H 114 115 JMenuItem indexItem = new JMenuItem("Index"); 116 indexItem.setMnemonic('I'); //为Help这个菜单设置快捷键I 117 helpMenu.add(indexItem);//将Index菜单项添加到Help这个菜单中 118 119 //也可以将助记键添加到动作中 120 TestAction aboutAction = new TestAction("About"); 121 aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A')); //为aboutAction对象添加快捷键A 122 helpMenu.add(aboutAction); 123 124 // 将所有顶级菜单添加到菜单栏 125 126 JMenuBar menuBar = new JMenuBar();//创建一个菜单栏 127 setJMenuBar(menuBar); 128 129 menuBar.add(fileMenu); 130 menuBar.add(editMenu); 131 menuBar.add(helpMenu); 132 133 // 演示弹出窗口 134 135 popup = new JPopupMenu(); //创建一个弹出菜单 136 popup.add(cutAction); 137 popup.add(copyAction); 138 popup.add(pasteAction); 139 140 JPanel panel = new JPanel(); 141 panel.setComponentPopupMenu(popup); //用户点击panel时弹出菜单 142 add(panel); 143 } 144 }
1 import java.awt.*; 2 import javax.swing.*; 3 4 /** 5 * @version 1.25 2018-04-10 6 * @author Cay Horstmann 7 */ 8 public class MenuTest 9 { 10 public static void main(String[] args) 11 { 12 EventQueue.invokeLater(() -> { 13 MenuFrame frame = new MenuFrame(); 14 frame.setTitle("MenuTest"); 15 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 frame.setVisible(true); 17 }); 18 } 19 }
运行结果如下:
测试程序2:
掌握工具栏和工具提示的用法
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 5 /** 6 * 带有工具栏和颜色变化菜单的框架 7 */ 8 public class ToolBarFrame extends JFrame 9 { 10 private static final int DEFAULT_WIDTH = 300; 11 private static final int DEFAULT_HEIGHT = 200; 12 private JPanel panel; 13 14 public ToolBarFrame() 15 { 16 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 17 18 // 添加用于颜色更改的面板 19 20 panel = new JPanel(); 21 add(panel, BorderLayout.CENTER);//将这个面板加在边框的中间 22 23 // 设置操作 24 25 ColorAction blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE); 26 ColorAction yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),Color.YELLOW); 27 ColorAction redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); 28 29 AbstractAction exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif")) 30 { 31 public void actionPerformed(ActionEvent event) 32 { 33 System.exit(0); 34 } 35 }; 36 exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit"); 37 38 // 填充工具栏 39 40 JToolBar bar = new JToolBar(); //创建一个工具栏 41 bar.add(blueAction); 42 bar.add(yellowAction); 43 bar.add(redAction); 44 bar.addSeparator(); //给工具栏添加分隔符 45 bar.add(exitAction); 46 add(bar, BorderLayout.NORTH); 47 48 //填充菜单 49 50 JMenu menu = new JMenu("Color"); 51 menu.add(yellowAction); 52 menu.add(blueAction); 53 menu.add(redAction); 54 menu.add(exitAction); 55 JMenuBar menuBar = new JMenuBar();//创建菜单栏 56 menuBar.add(menu);//将菜单栏加到菜单上 57 setJMenuBar(menuBar); 58 } 59 60 /** 61 * 颜色动作将框架的背景设置为给定的颜色. 62 */ 63 class ColorAction extends AbstractAction 64 { 65 public ColorAction(String name, Icon icon, Color c) 66 { 67 putValue(Action.NAME, name); 68 putValue(Action.SMALL_ICON, icon); 69 putValue(Action.SHORT_DESCRIPTION, name + " background"); 70 putValue("Color", c); 71 } 72 73 public void actionPerformed(ActionEvent event) 74 { 75 Color c = (Color) getValue("Color"); 76 panel.setBackground(c); //给面板加背景 77 } 78 } 79 }
1 import java.awt.*; 2 import javax.swing.*; 3 4 /** 5 * @version 1.15 2018-04-10 6 * @author Cay Horstmann 7 */ 8 public class ToolBarTest 9 { 10 public static void main(String[] args) 11 { 12 EventQueue.invokeLater(() -> { 13 ToolBarFrame frame = new ToolBarFrame(); 14 frame.setTitle("ToolBarTest"); 15 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 frame.setVisible(true); 17 }); 18 } 19 }
运行结果如下:
测试程序3:
掌握选项对话框的用法
1 import java.awt.*; 2 import java.awt.event.*; 3 import java.awt.geom.*; 4 import java.awt.geom.Rectangle2D.Double; 5 import java.util.*; 6 import javax.swing.*; 7 /** 8 * 包含用于选择各种选项对话框的设置的框架。 9 */ 10 public class OptionDialogFrame extends JFrame 11 { 12 private ButtonPanel typePanel; 13 private ButtonPanel messagePanel; 14 private ButtonPanel messageTypePanel; 15 private ButtonPanel optionTypePanel; 16 private ButtonPanel optionsPanel; 17 private ButtonPanel inputPanel; 18 private String messageString = "Message"; 19 private Icon messageIcon = new ImageIcon("blue-ball.gif"); 20 private Object messageObject = new Date(); 21 private Component messageComponent = new SampleComponent(); 22 23 public OptionDialogFrame() 24 { 25 JPanel gridPanel = new JPanel(); 26 gridPanel.setLayout(new GridLayout(2, 3));//设置该面板的布局管理器为2行3列的网格 27 28 typePanel = new ButtonPanel("Type", "Message", "Confirm", "Option", "Input"); 29 messageTypePanel = new ButtonPanel("Message Type", "ERROR_MESSAGE", "INFORMATION_MESSAGE", 30 "WARNING_MESSAGE", "QUESTION_MESSAGE", "PLAIN_MESSAGE"); 31 messagePanel = new ButtonPanel("Message", "String", "Icon", "Component", "Other", 32 "Object[]"); 33 optionTypePanel = new ButtonPanel("Confirm", "DEFAULT_OPTION", "YES_NO_OPTION", 34 "YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION"); 35 optionsPanel = new ButtonPanel("Option", "String[]", "Icon[]", "Object[]"); 36 inputPanel = new ButtonPanel("Input", "Text field", "Combo box"); 37 38 gridPanel.add(typePanel); 39 gridPanel.add(messageTypePanel); 40 gridPanel.add(messagePanel); 41 gridPanel.add(optionTypePanel); 42 gridPanel.add(optionsPanel); 43 gridPanel.add(inputPanel); 44 45 // 添加带有显示按钮的面板 46 47 JPanel showPanel = new JPanel(); 48 JButton showButton = new JButton("Show"); 49 showButton.addActionListener(new ShowAction()); 50 showPanel.add(showButton);//把按钮添加到面板上 51 52 add(gridPanel, BorderLayout.CENTER); 53 add(showPanel, BorderLayout.SOUTH); 54 pack(); 55 } 56 57 /** 58 * Gets the currently selected message. 59 * @return a string, icon, component, or object array, depending on the Message panel selection 60 */ 61 public Object getMessage() 62 { 63 String s = messagePanel.getSelection(); 64 if (s.equals("String")) return messageString; 65 else if (s.equals("Icon")) return messageIcon; 66 else if (s.equals("Component")) return messageComponent; 67 else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon, 68 messageComponent, messageObject }; 69 else if (s.equals("Other")) return messageObject; 70 else return null; 71 } 72 73 /** 74 * Gets the currently selected options. 75 * @return an array of strings, icons, or objects, depending on the Option panel selection 76 */ 77 public Object[] getOptions() 78 { 79 String s = optionsPanel.getSelection(); 80 if (s.equals("String[]")) return new String[] { "Yellow", "Blue", "Red" }; 81 else if (s.equals("Icon[]")) return new Icon[] { new ImageIcon("yellow-ball.gif"), 82 new ImageIcon("blue-ball.gif"), new ImageIcon("red-ball.gif") }; 83 else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon, 84 messageComponent, messageObject }; 85 else return null; 86 } 87 88 /** 89 * Gets the selected message or option type 90 * @param panel the Message Type or Confirm panel 91 * @return the selected XXX_MESSAGE or XXX_OPTION constant from the JOptionPane class 92 */ 93 public int getType(ButtonPanel panel) 94 { 95 String s = panel.getSelection(); 96 try 97 { 98 return JOptionPane.class.getField(s).getInt(null); 99 } 100 catch (Exception e) 101 { 102 return -1; 103 } 104 } 105 106 /** 107 * The action listener for the Show button shows a Confirm, Input, Message, or Option dialog 108 * depending on the Type panel selection. 109 */ 110 private class ShowAction implements ActionListener 111 { 112 public void actionPerformed(ActionEvent event) 113 { 114 if (typePanel.getSelection().equals("Confirm")) JOptionPane.showConfirmDialog( //显示确认对话框 115 OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel), 116 getType(messageTypePanel)); 117 else if (typePanel.getSelection().equals("Input")) 118 { 119 if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog(//显示输入对话框 120 OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel)); 121 else JOptionPane.showInputDialog(OptionDialogFrame.this, getMessage(), "Title", 122 getType(messageTypePanel), null, new String[] { "Yellow", "Blue", "Red" }, 123 "Blue"); 124 } 125 else if (typePanel.getSelection().equals("Message")) JOptionPane.showMessageDialog(//显示信息对话框 126 OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel)); 127 else if (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog(//显示选择对话框 128 OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel), 129 getType(messageTypePanel), null, getOptions(), getOptions()[0]); 130 } 131 } 132 } 133 134 /** 135 * A component with a painted surface 136 */ 137 138 class SampleComponent extends JComponent 139 { 140 public void paintComponent(Graphics g) 141 { 142 Graphics2D g2 = (Graphics2D) g; 143 Double rect = new Rectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1); 144 g2.setPaint(Color.YELLOW); 145 g2.fill(rect); 146 g2.setPaint(Color.BLUE); 147 g2.draw(rect); 148 } 149 150 public Dimension getPreferredSize() 151 { 152 return new Dimension(10, 10); 153 } 154 }
1 import javax.swing.*; 2 3 /** 4 * A panel with radio buttons inside a titled border. 5 */ 6 public class ButtonPanel extends JPanel 7 { 8 private ButtonGroup group; 9 10 /** 11 * Constructs a button panel. 12 * @param title the title shown in the border 13 * @param options an array of radio button labels 14 */ 15 public ButtonPanel(String title, String... options) 16 { 17 setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));//创建一个带标题的边框 18 setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); 19 group = new ButtonGroup(); 20 21 // 为每个选项制作一个单选按钮 22 for (String option : options) 23 { 24 JRadioButton button = new JRadioButton(option); 25 button.setActionCommand(option); 26 add(button); 27 group.add(button); 28 button.setSelected(option == options[0]); 29 } 30 } 31 32 /** 33 * Gets the currently selected option. 34 * @return the label of the currently selected radio button. 35 */ 36 public String getSelection() 37 { 38 return group.getSelection().getActionCommand(); 39 } 40 }
1 import java.awt.*; 2 import javax.swing.*; 3 4 /** 5 * @version 1.35 2018-04-10 6 * @author Cay Horstmann 7 */ 8 public class OptionDialogTest 9 { 10 public static void main(String[] args) 11 { 12 EventQueue.invokeLater(() -> { 13 OptionDialogFrame frame = new OptionDialogFrame(); 14 frame.setTitle("OptionDialogTest"); 15 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 frame.setVisible(true); 17 }); 18 } 19 }
运行结果如下:
测试程序4:
掌握对话框的创建方法
1 import javax.swing.JFrame; 2 import javax.swing.JMenu; 3 import javax.swing.JMenuBar; 4 import javax.swing.JMenuItem; 5 6 /** 7 * A frame with a menu whose File->About action shows a dialog. 8 */ 9 public class DialogFrame extends JFrame 10 { 11 private static final int DEFAULT_WIDTH = 300; 12 private static final int DEFAULT_HEIGHT = 200; 13 private AboutDialog dialog; 14 15 public DialogFrame() 16 { 17 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 18 19 // 构造文件菜单 20 21 JMenuBar menuBar = new JMenuBar();//创建一个菜单栏 22 setJMenuBar(menuBar); 23 JMenu fileMenu = new JMenu("File"); 24 menuBar.add(fileMenu);//将File菜单添加到菜单栏上 25 26 // 添加和退出菜单项 27 28 // About项目显示About对话框 29 30 JMenuItem aboutItem = new JMenuItem("About"); 31 aboutItem.addActionListener(event -> { 32 if (dialog == null) // first time 33 dialog = new AboutDialog(DialogFrame.this); 34 dialog.setVisible(true); // 弹出对话框 35 }); 36 fileMenu.add(aboutItem); 37 38 // 退出项目退出程序 39 40 JMenuItem exitItem = new JMenuItem("Exit"); 41 exitItem.addActionListener(event -> System.exit(0)); 42 fileMenu.add(exitItem);//将菜单项添加到菜单上 43 } 44 }
1 import java.awt.*; 2 import javax.swing.*; 3 4 /** 5 * @version 1.35 2018-04-10 6 * @author Cay Horstmann 7 */ 8 public class DialogTest 9 { 10 public static void main(String[] args) 11 { 12 EventQueue.invokeLater(() -> { 13 DialogFrame frame = new DialogFrame(); 14 frame.setTitle("DialogTest"); 15 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 frame.setVisible(true); 17 }); 18 } 19 }
1 import java.awt.BorderLayout; 2 3 import javax.swing.JButton; 4 import javax.swing.JDialog; 5 import javax.swing.JFrame; 6 import javax.swing.JLabel; 7 import javax.swing.JPanel; 8 9 /** 10 * A sample modal dialog that displays a message and waits for the user to click 11 * the OK button. 12 */ 13 public class AboutDialog extends JDialog 14 { 15 public AboutDialog(JFrame owner) 16 { 17 super(owner, "About DialogTest", true); 18 19 //将html标签添加到中心 20 21 add( 22 new JLabel( 23 "<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"), 24 BorderLayout.CENTER); 25 26 // ok按钮关闭对话框 27 28 JButton ok = new JButton("OK"); 29 ok.addActionListener(event -> setVisible(false)); 30 31 // 将“ok”按钮添加到南部边框 32 33 JPanel panel = new JPanel(); 34 panel.add(ok); 35 add(panel, BorderLayout.SOUTH); 36 pack(); 37 } 38 }
运行结果如下:
测试程序5:
掌握对话框的数据交换用法;
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 5 /** 6 * A frame with a menu whose File->Connect action shows a password dialog. 7 */ 8 public class DataExchangeFrame extends JFrame 9 { 10 public static final int TEXT_ROWS = 20; 11 public static final int TEXT_COLUMNS = 40; 12 private PasswordChooser dialog = null; 13 private JTextArea textArea; 14 15 public DataExchangeFrame() 16 { 17 // 构建文件菜单 18 19 JMenuBar mbar = new JMenuBar();//创建一个菜单栏 20 setJMenuBar(mbar); 21 JMenu fileMenu = new JMenu("File"); //创建一个菜单 22 mbar.add(fileMenu);//在菜单栏中添加菜单 23 24 // 添加连接和退出菜单项 25 26 JMenuItem connectItem = new JMenuItem("Connect");//创建一个菜单项 27 connectItem.addActionListener(new ConnectAction()); 28 fileMenu.add(connectItem);//将菜单项添加到菜单 29 30 // Exit项目退出程序 31 32 JMenuItem exitItem = new JMenuItem("Exit"); 33 exitItem.addActionListener(event -> System.exit(0)); 34 fileMenu.add(exitItem); 35 36 textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS); 37 add(new JScrollPane(textArea), BorderLayout.CENTER);//为文本区添加滚动条并放在边框的中间 38 pack(); 39 } 40 41 /** 42 * The Connect action pops up the password dialog. 43 */ 44 private class ConnectAction implements ActionListener 45 { 46 public void actionPerformed(ActionEvent event) 47 { 48 // 如果第一次构建对话框 49 50 if (dialog == null) dialog = new PasswordChooser(); 51 52 // 设置默认值 53 dialog.setUser(new User("yourname", null)); 54 55 // 弹出对话框 56 if (dialog.showDialog(DataExchangeFrame.this, "Connect")) 57 { 58 // 如果接受,检索用户输入 59 User u = dialog.getUser(); 60 textArea.append("user name = " + u.getName() + ", password = " 61 + (new String(u.getPassword())) + " "); 62 } 63 } 64 } 65 }
1 import java.awt.*; 2 import javax.swing.*; 3 4 /** 5 * @version 1.35 2018-04-10 6 * @author Cay Horstmann 7 */ 8 public class DataExchangeTest 9 { 10 public static void main(String[] args) 11 { 12 EventQueue.invokeLater(() -> { 13 DataExchangeFrame frame = new DataExchangeFrame(); 14 frame.setTitle("DataExchangeTest"); 15 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 frame.setVisible(true); 17 }); 18 } 19 }
1 import java.awt.BorderLayout; 2 import java.awt.Component; 3 import java.awt.Frame; 4 import java.awt.GridLayout; 5 6 import javax.swing.JButton; 7 import javax.swing.JDialog; 8 import javax.swing.JLabel; 9 import javax.swing.JPanel; 10 import javax.swing.JPasswordField; 11 import javax.swing.JTextField; 12 import javax.swing.SwingUtilities; 13 14 /** 15 * A password chooser that is shown inside a dialog. 16 */ 17 public class PasswordChooser extends JPanel 18 { 19 private JTextField username; 20 private JPasswordField password; 21 private JButton okButton; 22 private boolean ok; 23 private JDialog dialog; 24 25 public PasswordChooser() 26 { 27 setLayout(new BorderLayout()); 28 29 // 构建一个包含用户名和密码字段的面板 30 31 JPanel panel = new JPanel(); 32 panel.setLayout(new GridLayout(2, 2));//设置面板的布局管理器为2*2的网格 33 panel.add(new JLabel("User name:")); 34 panel.add(username = new JTextField(""));//给面板添加文本域 35 panel.add(new JLabel("Password:")); 36 panel.add(password = new JPasswordField("")); 37 add(panel, BorderLayout.CENTER);//将该面板添加到边框的中间 38 39 // 创建终止对话框的“确定”和“取消”按钮 40 41 okButton = new JButton("Ok"); 42 okButton.addActionListener(event -> { 43 ok = true; 44 dialog.setVisible(false); 45 }); 46 47 JButton cancelButton = new JButton("Cancel"); 48 cancelButton.addActionListener(event -> dialog.setVisible(false)); 49 50 // 向南部边框添加按钮 51 52 JPanel buttonPanel = new JPanel(); 53 buttonPanel.add(okButton); 54 buttonPanel.add(cancelButton); 55 add(buttonPanel, BorderLayout.SOUTH); 56 } 57 58 /** 59 * Sets the dialog defaults. 60 * @param u the default user information 61 */ 62 public void setUser(User u) 63 { 64 username.setText(u.getName()); 65 } 66 67 /** 68 * Gets the dialog entries. 69 * @return a User object whose state represents the dialog entries 70 */ 71 public User getUser() 72 { 73 return new User(username.getText(), password.getPassword()); 74 } 75 76 /** 77 * Show the chooser panel in a dialog. 78 * @param parent a component in the owner frame or null 79 * @param title the dialog window title 80 */ 81 public boolean showDialog(Component parent, String title) 82 { 83 ok = false; 84 85 // 定位到owner 框架 86 87 Frame owner = null; 88 if (parent instanceof Frame) 89 owner = (Frame) parent; 90 else 91 owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent); 92 93 //如果是第一次,或者owner已经更改,请创建新对话框 94 95 if (dialog == null || dialog.getOwner() != owner) 96 { 97 dialog = new JDialog(owner, true); 98 dialog.add(this); 99 dialog.getRootPane().setDefaultButton(okButton); 100 dialog.pack(); 101 } 102 103 // 设置标题和显示对话框 104 105 dialog.setTitle(title); 106 dialog.setVisible(true); 107 return ok; 108 } 109 }
1 /** 2 * A user has a name and password. For security reasons, the password is stored as a char[], not a 3 * String. 4 */ 5 public class User 6 { 7 private String name; 8 private char[] password; 9 10 public User(String aName, char[] aPassword) 11 { 12 name = aName; 13 password = aPassword; 14 } 15 16 public String getName() 17 { 18 return name; 19 } 20 21 public char[] getPassword() 22 { 23 return password; 24 } 25 26 public void setName(String aName) 27 { 28 name = aName; 29 } 30 31 public void setPassword(char[] aPassword) 32 { 33 password = aPassword; 34 } 35 }
运行结果如下:
测试程序6:
掌握文件对话框的用法
1 import java.io.*; 2 3 import javax.swing.*; 4 import javax.swing.filechooser.*; 5 import javax.swing.filechooser.FileFilter; 6 7 /** 8 * A frame that has a menu for loading an image and a display area for the 9 * loaded image. 10 */ 11 public class ImageViewerFrame extends JFrame 12 { 13 private static final int DEFAULT_WIDTH = 300; 14 private static final int DEFAULT_HEIGHT = 400; 15 private JLabel label; 16 private JFileChooser chooser; 17 18 public ImageViewerFrame() 19 { 20 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 21 22 // 设置菜单栏 23 JMenuBar menuBar = new JMenuBar(); 24 setJMenuBar(menuBar); 25 26 JMenu menu = new JMenu("File"); 27 menuBar.add(menu); 28 29 JMenuItem openItem = new JMenuItem("Open"); 30 menu.add(openItem); 31 openItem.addActionListener(event -> { 32 chooser.setCurrentDirectory(new File(".")); 33 34 // 显示文件选择器对话框 35 int result = chooser.showOpenDialog(ImageViewerFrame.this); 36 37 // 如果图像文件被接受,将其设置为标签的图标 38 if (result == JFileChooser.APPROVE_OPTION) 39 { 40 String name = chooser.getSelectedFile().getPath(); 41 label.setIcon(new ImageIcon(name)); 42 pack(); 43 } 44 }); 45 46 JMenuItem exitItem = new JMenuItem("Exit"); 47 menu.add(exitItem); 48 exitItem.addActionListener(event -> System.exit(0)); 49 50 // 使用标签显示图像 51 label = new JLabel(); 52 add(label); 53 54 // 设置文件选择器 55 chooser = new JFileChooser(); 56 57 // 接受所有以jpg,jpeg ,gif结尾的图像文件 58 FileNameExtensionFilter filter = new FileNameExtensionFilter( 59 "Image files", "jpg", "jpeg", "gif"); 60 chooser.setFileFilter(filter); 61 62 chooser.setAccessory(new ImagePreviewer(chooser)); 63 64 chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif"))); 65 } 66 }
1 import java.awt.*; 2 import java.io.*; 3 4 import javax.swing.*; 5 6 /** 7 * A file chooser accessory that previews images. 8 */ 9 public class ImagePreviewer extends JLabel 10 { 11 /** 12 * Constructs an ImagePreviewer. 13 * @param chooser the file chooser whose property changes trigger an image 14 * change in this previewer 15 */ 16 public ImagePreviewer(JFileChooser chooser) 17 { 18 setPreferredSize(new Dimension(100, 100)); 19 setBorder(BorderFactory.createEtchedBorder()); 20 21 chooser.addPropertyChangeListener(event -> { 22 if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) 23 { 24 // 用户选择了一个新文件 25 File f = (File) event.getNewValue(); 26 if (f == null) 27 { 28 setIcon(null); 29 return; 30 } 31 32 // 将图像读入图标 33 ImageIcon icon = new ImageIcon(f.getPath()); 34 35 // 如果图标太大,缩放它 36 if (icon.getIconWidth() > getWidth()) 37 icon = new ImageIcon(icon.getImage().getScaledInstance( 38 getWidth(), -1, Image.SCALE_DEFAULT)); 39 40 setIcon(icon); 41 } 42 }); 43 } 44 }
1 import java.io.*; 2 import javax.swing.*; 3 import javax.swing.filechooser.*; 4 import javax.swing.filechooser.FileFilter; 5 6 /** 7 *显示与文件过滤器匹配的所有文件的图标的文件视图。 8 */ 9 public class FileIconView extends FileView 10 { 11 private FileFilter filter; 12 private Icon icon; 13 14 /** 15 * Constructs a FileIconView. 16 * @param aFilter a file filter--all files that this filter accepts will be shown 17 * with the icon. 18 * @param anIcon--the icon shown with all accepted files. 19 */ 20 public FileIconView(FileFilter aFilter, Icon anIcon) 21 { 22 filter = aFilter; 23 icon = anIcon; 24 } 25 26 public Icon getIcon(File f) 27 { 28 if (!f.isDirectory() && filter.accept(f)) return icon; 29 else return null; 30 } 31 }
1 import java.awt.*; 2 import javax.swing.*; 3 4 /** 5 * @version 1.26 2018-04-10 6 * @author Cay Horstmann 7 */ 8 public class FileChooserTest 9 { 10 public static void main(String[] args) 11 { 12 EventQueue.invokeLater(() -> { 13 ImageViewerFrame frame = new ImageViewerFrame(); 14 frame.setTitle("FileChooserTest"); 15 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 frame.setVisible(true); 17 }); 18 } 19 }
运行结果如下:
测试程序7:
了解颜色选择器的用法
1 package 第十五周; 2 import javax.swing.*; 3 4 /** 5 * A frame with a color chooser panel 6 */ 7 public class ColorChooserFrame extends JFrame 8 { 9 private static final int DEFAULT_WIDTH = 300; //两个私有属性,常量 10 private static final int DEFAULT_HEIGHT = 200; 11 12 public ColorChooserFrame() //ColorChooserFrame构造器 13 { 14 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); //设置为两个常量大小的框架 15 16 // add color chooser panel to frame 17 18 ColorChooserPanel panel = new ColorChooserPanel(); //创建一个ColorChooserPanel类对象panel 19 add(panel); //将panel添加到框架里面 20 } 21 }
1 package 第十五周; 2 import java.awt.Color; 3 import java.awt.Frame; 4 import java.awt.event.ActionEvent; 5 import java.awt.event.ActionListener; 6 7 import javax.swing.JButton; 8 import javax.swing.JColorChooser; 9 import javax.swing.JDialog; 10 import javax.swing.JPanel; 11 12 /** 13 * A panel with buttons to pop up three types of color choosers 14 */ 15 public class ColorChooserPanel extends JPanel 16 { 17 public ColorChooserPanel() //ColorChooserPanel构造器 18 { 19 JButton modalButton = new JButton("Modal"); //创建一个JButton按钮对象 20 modalButton.addActionListener(new ModalListener()); //动作监听器对象 21 add(modalButton); //将JButton对象添加到框架里面 22 23 JButton modelessButton = new JButton("Modeless"); //新建一个Modeless按钮 24 modelessButton.addActionListener(new ModelessListener()); //添加动作监听器 25 add(modelessButton); //将按钮添加到框架当中 26 27 JButton immediateButton = new JButton("Immediate"); //新建一个Immediate按钮 28 immediateButton.addActionListener(new ImmediateListener()); //添加动作监听器 29 add(immediateButton); //将immediateButton添加到框架当中 30 } 31 32 /** 33 * This listener pops up a modal color chooser 34 */ 35 private class ModalListener implements ActionListener //创建一个实现ActionListener接口的类ModalListener 36 { 37 public void actionPerformed(ActionEvent event) //actionPerformed方法 38 { 39 Color defaultColor = getBackground(); //创建一个颜色类对象,设置为背景颜色 40 Color selected = JColorChooser.showDialog(ColorChooserPanel.this, "Set background", 41 defaultColor); 42 if (selected != null) setBackground(selected); 43 } 44 } 45 46 /** 47 * This listener pops up a modeless color chooser. The panel color is changed when the user 48 * clicks the OK button. 49 */ 50 private class ModelessListener implements ActionListener //ModelessListener类实现了ActionListener接口 51 { 52 private JDialog dialog; //对话框 53 private JColorChooser chooser; //颜色选择器 54 55 public ModelessListener() //ModelessListener构造器 56 { 57 chooser = new JColorChooser(); //创建一个JColorChooser选择器类对象 58 dialog = JColorChooser.createDialog(ColorChooserPanel.this, "Background Color", 59 false /* not modal */, chooser, 60 event -> setBackground(chooser.getColor()), 61 null /* no Cancel button listener */); 62 }//创建一个对话框,颜色选择器面板ColorChooserPanel.this是本类,提供组件。设置背景颜色为颜色选择器调用getColor方法得到的颜色 63 64 public void actionPerformed(ActionEvent event) //actionPerformed方法 65 { 66 chooser.setColor(getBackground()); //设置背景颜色 67 dialog.setVisible(true); //设置对话框组件可见 68 } 69 } 70 71 /** 72 * This listener pops up a modeless color chooser. The panel color is changed immediately when 73 * the user picks a new color. 74 */ 75 private class ImmediateListener implements ActionListener //ImmediateListener是实现ActionListener接口的类 76 { 77 private JDialog dialog; 78 private JColorChooser chooser; //私有属性,颜色选择器的定义 79 80 public ImmediateListener() //ImmediateListener构造器 81 { 82 chooser = new JColorChooser(); //新建一个颜色选择器类对象 83 chooser.getSelectionModel().addChangeListener( 84 event -> setBackground(chooser.getColor())); 85 86 dialog = new JDialog((Frame) null, false /* not modal */); 87 dialog.add(chooser);//添加chooser到文本框当中 88 dialog.pack(); //获取对话框的首选大小 89 } 90 91 public void actionPerformed(ActionEvent event)//actionPerformed方法 92 { 93 chooser.setColor(getBackground()); //设置背景颜色 94 dialog.setVisible(true); //设置组件可见 95 } 96 } 97 }
1 package 第十五周; 2 import java.awt.*; 3 import javax.swing.*; 4 5 /** 6 * @version 1.04 2015-06-12 7 * @author Cay Horstmann 8 */ 9 public class ColorChooserTest //框架整体框架 10 { 11 public static void main(String[] args) 12 { 13 EventQueue.invokeLater(() -> { 14 JFrame frame = new ColorChooserFrame(); 15 frame.setTitle("ColorChooserTest"); 16 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 17 frame.setVisible(true); 18 }); 19 } 20 }
运行结果如下:
实验总结:
本周重点学了菜单和对话框,包括在菜单栏上添加菜单项,嵌套菜单,以及弹出菜单的使用,还有对话框的很多类型,有选择对话框,确认对话框,消息对话框,还有确认对话框。本周的实验都是验证性实验,通过看书,注释,网上查找,还有问同学就感觉是懂了点,但是理解的还不是很透彻,我会在课余时间自己看着书多敲几遍,多理解理解。