201871010136-赵艳强《面向对象程序设计JAVA》第十五周实验总结
项目 |
内容 |
这个作业属于哪个课程 |
https://www.cnblogs.com/nwnu-daizh |
这个作业的要求在哪里 |
https://www.cnblogs.com/nwnu-daizh/p/11995615.html |
这个作业的目标是什么 |
|
第一部分 基础知识总结
(一)菜单
1.菜单创建
Swing菜单由菜单条(JMenuBar)、菜单(JMenu)和菜单项(JMenuItem)构成。菜单条是所有菜单和菜单项的根(容器)。
●创建一个菜单栏
JMenuBar menuBar=new JMenuBar();
●调用setJMenuBar方法将菜单栏添加到框架上
frame.setJMenuBar(menuBar);
●为每个菜单建立一个菜单对象
JMenu editMenu=new JMenu("Edit");
●将顶层菜单添加到菜单栏中
1
|
menuBar.add(editMenu); |
●向菜单对象中添加菜单项,分隔符,子菜单
1
2
3
4
5
|
JMenuItem pasteItem= new JMenuItem( "Paste" ); deitMenu.add(pasteItem); editMenu.<br>addSeparator(); JMenu optionsMenu=...; //子菜单 editMenu.add(optionsMenu); |
2.菜单项中的图标
●利用JMenuItem(String.Icon)或JMenuItem(Icon)构造器为菜单指定一个图标,也可以利用JMenuItem类的setIcon方法(继承自AbstractButton类)指定一个图标
1
|
JMenuItem cutItem= new JMenuItem( "Cut" , new ImageIcon( "cut.gif" )); |
3.复选框和单选按钮菜单项
●创建复选框菜单项的代码
1
2
|
JCheckBosMenuItem readonlyItem= new JCheckBoxMenuItem( "Read-only" ); optionsMenu.add(readonlyItem); |
4.弹出菜单
创建
1
|
JPopupMenu popup= new JPopupMenu(); |
添加菜单项
1
2
3
|
JMenuItem item= new JMenuItem( "Cut" ); item.addActionListener(listener); popup.add(item); |
5.快捷键和加速器
●可以通过在菜单项的构造器中指定一个快捷字母来为菜单项设置快捷键
1
|
JMenuItem aboutItem= new JMenuItem( "Aoubt" , 'A' ); |
快捷键会自动显示在菜单项中,并带有一条下划线("About"),如果字母没有出现在菜单项标签字符串中,同样可以按下快捷键选择菜单项,只是快捷键没有显示出来
可以调用setDisplayedMnemonicIndex方法指定希望加下划线的字符
●只能在菜单项的构造器中设定快捷键字母,而不是菜单构造器中,如果想为菜单设置快捷键,需调用setMnemonic方法
1
2
|
JMenu helpMenu= new JMenu( "Help" ); helpMenu.setMnemonic( 'H' ); |
●可以为菜单项添加加速器,加速器只能关联到菜单项上,加速器并不实际打开菜单,而是直接激活菜单关联的动作事件
1
|
openItem.setAccelerator(KeyStroke.getKeyStroke( "ctrl O" )); |
6.启用和禁用菜单项
有些时候,某个特定的菜单项可能只能够在特定的环境下可用,例如,当文档以只读方式打开时,save菜单项就没有意义了
●启用或禁用菜单项需调用setEnabled方法
●启用和禁用菜单项有两个策略
①只要当文档以只读方式打开,就禁用save和save as
②在显示菜单之前禁用菜单项,这里必须为"menuselected"事件注册监听器
javax.swing.event包定义了MenuListener接口,包含3个方法
1
2
3
|
void menuSelected(MenuEvent event ) void menuDeselected(MenuEvent event ) void menuCanceled(MenuEvent event ) |
7.工具栏 JToolBar
工具栏只有位于采用边框布局或任何支持North,East,South,West约束布局管理器的容器内才可拖拽
将组件添加到工具栏中
1
2
|
JToolBar bar= new JToolBar(); bar.add(blueButton): |
1.可以添加一个Action对象,从而添加一个指派动作的新JButton 2.可以用分隔符将按钮分组 3.将工具栏添加到框架中 4.为工具栏指定标题 5.垂直放置
8.工具提示
调用setToolText方法
如果使用Action对象,也可以用SHORT_DESCRIPTION关联工具提示
(二)对话框
1.选项对话框
[API] javax.swing.JOptionPane
●JOptionPane有4个显示对话框的基本方法
showMessageDialog //显示一条消息并等待用户点击OK
showConfirmDialog //显示一条消息并等待用户确认(与OK/Cancel类似)
showOptionDialog //显示一条消息并获得用户在一组选项中的选择
showInputDialog //显示一条消息并获得用户输入的一行文本
(1)选择对话框的类型(消息、确认、选项或者输入)
(2)选择图标(错误、信息、警告、问题、无或者自定义)
(3)选择消息(字符串、图标、自定义组件或者它们的集合)
(4)对于确认对话框,选择选项类型(默认、Yes/No、Yes/No/Cancel或者OK/Cancel)
(5)对于选项对话框,选择选项(字符串、图表或者自定义组件)和默认选项
(6)对于输入对话框,选择文本框或者组合框
(7)调用JOptionPane API 中的相应方法
2.创建对话框
(1)在对话框构造器中,调用超类JDialog的构造器,需提供拥有者框架,对话框标题,特征
拥有者框架控制对话框的显示位置,如果拥有者标识为null,则对话框将由一个隐藏框架所拥有
特征是指定对话框处于显示状态时,应用程序中其他窗口是否被锁住
(2)添加对话框的用户界面组件
(3)添加事件处理器
(4)设置对话框的大小
3.数据交换
[API] javax.swing.SwingUtillities
[API] javax.swing.JComponent
[API] javax.swing.JRootPane
[API] javax.swing.JButton
●对话框应提供设置默认数据的方法
●一旦设置了默认值,就可调用setVisible(true)让对话框显示在屏幕上
●点击OK/Cancel后,这两个按钮的事件处理器都会调用setVisible(false)终止显示
●希望知道用户是接收对话框还是取消对话框,在示例中设置了OK标志,在对话框显示之前是false,只有OK事件处理器可以设置为true
●示例中还包含另外一个改进,在构造一个JDialog对象时,需指定拥有者框架,但是,很多情况下,一个对话框可能有多个拥有者,所以最好准备显示对话框时再确认拥有者框架,一个技巧是让PasswordChoose扩展与JPanel,而不是JDialog
4.文件对话框
文件对话框 JFileChooser
●JFileChooser是一个模式对话框,但并不是JDialog类的子类
●需要调用showOpenDialog,而不是setVisible(true)显示打开文件的对话框,或调用showSaveDialog显示保存文件对话框
●接收文件的按钮自动标签为Open或Save,也可调用showDialog方法为按钮设定标签
(1)建立一个JFileChooser对象,与JDialog类的构造器不同,它不需要指定父组件,允许在多个框架中重用一个文件选择器
JFileChooser chooser=new JFileChooser();
(2)调用setCurrentDirectory方法设置当前目录
chooser.setCurrentDirectory(new File("."));
(3)如果有一个想要作为用户选择的默认文件名,可以使用setSelectedFile方法指定
chooser.setSelectedFile(new File(filename));
(4)如果允许用户选择多个文件,需调用setMultiSelectionEnabled方法
chooser.setMultiSelectionEnabled(true);
(5)如果想让对话框仅显示某一种类型的文件,需设置文件过滤器
●若想限制显示的文件,需创建一个实现了抽象类javax.swing.filechooser.FileFilter对象,文件选择器将每个文件传递给文件过滤器,只有文件过滤器接受的文件才被最终显示出来
●一旦有了文件过滤器对象,就可以调用JFileChooser类中的setFileFilter方法,将这个对象安装到文件选择器对象中
choose.setFileFilter(new FileNameExtensionFilter("Image files","gif","jpg");
●可以为一个文件选择器安装多个过滤器
chosser.addChoosableFileFilter(filter1); chosser.addChoosableFileFilter(filter2);
●用户可以从文件对话框底部的组合框中选择过滤器,在默认情况下,All files过滤器总是显示在组合框中,然而,如果你想放弃All files过滤器,需调用
chooser.setAccrpyAllFileFilterUsed(false);
如果为加载和保存不同类型的文件重用一个文件选择器,就需调用
chooser.resetChoosableFilters()
这样可以在添加新文件过滤器之前清除旧文件过滤器
(6)在默认情况下,用户在文件选择器中只能选择文件,如果希望选择目录,需调用setFileSelectionMode方法,参数值为:JFileChoose.FILES_ONLY(默认值),JFileChooser.DIRECTORIES_ONLY或者JFileChooser.FILES_AND_DIRECTORIES
(7)调用showOpenDialog或showSaveDialog方法显示对话框,必须为这些调用提供父组件
int result=chooser.showOpenDialog(parent); int result=chooser.showSaveDialog(parent);
●也可以调用showDialog方法,将一个显式文本传递给确认按钮
int result=chooser.showDialog(parent,"Select");
当且仅当用户确认、取消、离开对话框时才返回调用,返回值可以是JFileChooser.APPROVE_OPTION、JFileChooser.CANCEL_OPTION或者JFileChooser.ERROR_OPTION
(8)调用getSelectedFile()或getSelectedFiles()方法获取用户选择的一个或多个文件,这些方法将返回一个文件对象或一组文件对象,如需知道文件对象名,可以调用getPath方法
String filename=chooser.getSelectedFile().getPath();
5.颜色选择器
颜色选择器 JColorChooser
●利用颜色选择器显示模式对话框
Color selectedColor=JColorChooser.showDialog(parent,title,initialColor);
●也可以显示无模式颜色选择器对话框,需提供
■ 一个父组件
■ 对话框的标题
■ 选择模式/无模式对话框的标志
■ 颜色选择器
■ OK和Canel按钮的监听器(如果不需要可以设置为null)
●可以将颜色选择器组件直接添加到一个无模式对话框中
dialog=new JDialge(parent,false /*not modal */); dialog.add(chooser); dialog.pack()
1、实验目的与要求
(1) 掌握菜单组件用途及常用API;
(2) 掌握对话框组件用途及常用API;
(3) 学习设计简单应用程序的GUI。
2、实验内容和步骤
实验1: 导入第12章示例程序,测试程序并进行组内讨论。
测试程序1
l 在elipse IDE中调试运行教材512页程序12-8,结合运行结果理解程序;
l 掌握菜单的创建、菜单事件监听器、复选框和单选按钮菜单项、弹出菜单以及快捷键和加速器的用法。
l 记录示例代码阅读理解中存在的问题与疑惑。
12-8 代码:
package menu; import java.awt.*; import javax.swing.*; /** * @version 1.25 2018-04-10 * @author Cay Horstmann */ public class MenuTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { MenuFrame frame = new MenuFrame(); frame.setTitle("MenuTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package menu; import java.awt.event.*; import javax.swing.*; /** * A frame with a sample menu bar. */ public class MenuFrame extends JFrame { private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; private Action saveAction; private Action saveAsAction; private JCheckBoxMenuItem readonlyItem; private JPopupMenu popup; /** * A sample action that prints the action name to System.out. */ class TestAction extends AbstractAction { public TestAction(String name) { super(name); } public void actionPerformed(ActionEvent event) { System.out.println(getValue(Action.NAME) + " selected."); } } public MenuFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); JMenu fileMenu = new JMenu("File"); fileMenu.add(new TestAction("New")); // demonstrate accelerators JMenuItem openItem = fileMenu.add(new TestAction("Open")); openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O")); fileMenu.addSeparator(); saveAction = new TestAction("Save"); JMenuItem saveItem = fileMenu.add(saveAction); saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S")); saveAsAction = new TestAction("Save As"); fileMenu.add(saveAsAction); fileMenu.addSeparator(); fileMenu.add(new AbstractAction("Exit") { public void actionPerformed(ActionEvent event) { System.exit(0); } }); // demonstrate checkbox and radio button menus readonlyItem = new JCheckBoxMenuItem("Read-only"); readonlyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { boolean saveOk = !readonlyItem.isSelected(); saveAction.setEnabled(saveOk); saveAsAction.setEnabled(saveOk); } }); ButtonGroup group = new ButtonGroup(); JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert"); insertItem.setSelected(true); JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype"); group.add(insertItem); group.add(overtypeItem); // demonstrate icons TestAction cutAction = new TestAction("Cut"); cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif")); TestAction copyAction = new TestAction("Copy"); copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif")); TestAction pasteAction = new TestAction("Paste"); pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif")); JMenu editMenu = new JMenu("Edit"); editMenu.add(cutAction); editMenu.add(copyAction); editMenu.add(pasteAction); // demonstrate nested menus JMenu optionMenu = new JMenu("Options"); optionMenu.add(readonlyItem); optionMenu.addSeparator(); optionMenu.add(insertItem); optionMenu.add(overtypeItem); editMenu.addSeparator(); editMenu.add(optionMenu); // demonstrate mnemonics JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('H'); JMenuItem indexItem = new JMenuItem("Index"); indexItem.setMnemonic('I'); helpMenu.add(indexItem); // you can also add the mnemonic key to an action TestAction aboutAction = new TestAction("About"); aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A')); helpMenu.add(aboutAction); // add all top-level menus to menu bar JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(helpMenu); // demonstrate pop-ups popup = new JPopupMenu(); popup.add(cutAction); popup.add(copyAction); popup.add(pasteAction); JPanel panel = new JPanel(); panel.setComponentPopupMenu(popup); add(panel); } }
运行结果:
测试程序2
l 在elipse IDE中调试运行教材517页程序12-9,结合运行结果理解程序;
l 掌握工具栏和工具提示的用法;
l 记录示例代码阅读理解中存在的问题与疑惑。
12-9 代码:
package toolBar; import java.awt.*; import javax.swing.*; /** * @version 1.15 2018-04-10 * @author Cay Horstmann */ public class ToolBarTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { ToolBarFrame frame = new ToolBarFrame(); frame.setTitle("ToolBarTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package toolBar; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * A frame with a toolbar and menu for color changes. */ public class ToolBarFrame extends JFrame { private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; private JPanel panel; public ToolBarFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // add a panel for color change panel = new JPanel(); add(panel, BorderLayout.CENTER); // set up actions ColorAction blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE); ColorAction yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"), Color.YELLOW); ColorAction redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); AbstractAction exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif")) { public void actionPerformed(ActionEvent event) { System.exit(0); } }; exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit"); // populate toolbar JToolBar bar = new JToolBar(); bar.add(blueAction); bar.add(yellowAction); bar.add(redAction); bar.addSeparator(); bar.add(exitAction); add(bar, BorderLayout.NORTH); // populate menu JMenu menu = new JMenu("Color"); menu.add(yellowAction); menu.add(blueAction); menu.add(redAction); menu.add(exitAction); JMenuBar menuBar = new JMenuBar(); menuBar.add(menu); setJMenuBar(menuBar); } /** * The color action sets the background of the frame to a given color. */ class ColorAction extends AbstractAction { public ColorAction(String name, Icon icon, Color c) { putValue(Action.NAME, name); putValue(Action.SMALL_ICON, icon); putValue(Action.SHORT_DESCRIPTION, name + " background"); putValue("Color", c); } public void actionPerformed(ActionEvent event) { Color c = (Color) getValue("Color"); panel.setBackground(c); } } }
其运行结果:
测试程序3
l 在elipse IDE中调试运行教材544页程序12-15、12-16,结合运行结果理解程序;
l 掌握选项对话框的用法。
l 记录示例代码阅读理解中存在的问题与疑惑。
代码如下:
package optionDialog; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.geom.Rectangle2D.Double; import java.util.*; import javax.swing.*; /** * A frame that contains settings for selecting various option dialogs. */ public class OptionDialogFrame extends JFrame { private ButtonPanel typePanel; private ButtonPanel messagePanel; private ButtonPanel messageTypePanel; private ButtonPanel optionTypePanel; private ButtonPanel optionsPanel; private ButtonPanel inputPanel; private String messageString = "Message"; private Icon messageIcon = new ImageIcon("blue-ball.gif"); private Object messageObject = new Date(); private Component messageComponent = new SampleComponent(); public OptionDialogFrame() { JPanel gridPanel = new JPanel(); gridPanel.setLayout(new GridLayout(2, 3)); typePanel = new ButtonPanel("Type", "Message", "Confirm", "Option", "Input"); messageTypePanel = new ButtonPanel("Message Type", "ERROR_MESSAGE", "INFORMATION_MESSAGE", "WARNING_MESSAGE", "QUESTION_MESSAGE", "PLAIN_MESSAGE"); messagePanel = new ButtonPanel("Message", "String", "Icon", "Component", "Other", "Object[]"); optionTypePanel = new ButtonPanel("Confirm", "DEFAULT_OPTION", "YES_NO_OPTION", "YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION"); optionsPanel = new ButtonPanel("Option", "String[]", "Icon[]", "Object[]"); inputPanel = new ButtonPanel("Input", "Text field", "Combo box"); gridPanel.add(typePanel); gridPanel.add(messageTypePanel); gridPanel.add(messagePanel); gridPanel.add(optionTypePanel); gridPanel.add(optionsPanel); gridPanel.add(inputPanel); // add a panel with a Show button JPanel showPanel = new JPanel(); JButton showButton = new JButton("Show"); showButton.addActionListener(new ShowAction()); showPanel.add(showButton); add(gridPanel, BorderLayout.CENTER); add(showPanel, BorderLayout.SOUTH); pack(); } /** * Gets the currently selected message. * @return a string, icon, component, or object array, depending on the Message panel selection */ public Object getMessage() { String s = messagePanel.getSelection(); if (s.equals("String")) return messageString; else if (s.equals("Icon")) return messageIcon; else if (s.equals("Component")) return messageComponent; else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon, messageComponent, messageObject }; else if (s.equals("Other")) return messageObject; else return null; } /** * Gets the currently selected options. * @return an array of strings, icons, or objects, depending on the Option panel selection */ public Object[] getOptions() { String s = optionsPanel.getSelection(); if (s.equals("String[]")) return new String[] { "Yellow", "Blue", "Red" }; else if (s.equals("Icon[]")) return new Icon[] { new ImageIcon("yellow-ball.gif"), new ImageIcon("blue-ball.gif"), new ImageIcon("red-ball.gif") }; else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon, messageComponent, messageObject }; else return null; } /** * Gets the selected message or option type * @param panel the Message Type or Confirm panel * @return the selected XXX_MESSAGE or XXX_OPTION constant from the JOptionPane class */ public int getType(ButtonPanel panel) { String s = panel.getSelection(); try { return JOptionPane.class.getField(s).getInt(null); } catch (Exception e) { return -1; } } /** * The action listener for the Show button shows a Confirm, Input, Message, or Option dialog * depending on the Type panel selection. */ private class ShowAction implements ActionListener { public void actionPerformed(ActionEvent event) { if (typePanel.getSelection().equals("Confirm")) JOptionPane.showConfirmDialog( OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel), getType(messageTypePanel)); else if (typePanel.getSelection().equals("Input")) { if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog( OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel)); else JOptionPane.showInputDialog(OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel), null, new String[] { "Yellow", "Blue", "Red" }, "Blue"); } else if (typePanel.getSelection().equals("Message")) JOptionPane.showMessageDialog( OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel)); else if (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog( OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel), getType(messageTypePanel), null, getOptions(), getOptions()[0]); } } } /** * A component with a painted surface */ class SampleComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; Double rect = new Rectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1); g2.setPaint(Color.YELLOW); g2.fill(rect); g2.setPaint(Color.BLUE); g2.draw(rect); } public Dimension getPreferredSize() { return new Dimension(10, 10); } }
package optionDialog; import java.awt.*; import javax.swing.*; /** * @version 1.35 2018-04-10 * @author Cay Horstmann */ public class OptionDialogTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { OptionDialogFrame frame = new OptionDialogFrame(); frame.setTitle("OptionDialogTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package optionDialog; import javax.swing.*; /** * A panel with radio buttons inside a titled border. */ public class ButtonPanel extends JPanel { private ButtonGroup group; /** * Constructs a button panel. * @param title the title shown in the border * @param options an array of radio button labels */ public ButtonPanel(String title, String... options) { setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title)); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); group = new ButtonGroup(); // make one radio button for each option for (String option : options) { JRadioButton button = new JRadioButton(option); button.setActionCommand(option); add(button); group.add(button); button.setSelected(option == options[0]); } } /** * Gets the currently selected option. * @return the label of the currently selected radio button. */ public String getSelection() { return group.getSelection().getActionCommand(); } }
程序的运行结果:
测试程序4
l 在elipse IDE中调试运行教材552页程序12-17、12-18,结合运行结果理解程序;
l 掌握对话框的创建方法;
l 记录示例代码阅读理解中存在的问题与疑惑。
代码如下:
package dialog; import java.awt.*; import javax.swing.*; /** * @version 1.35 2018-04-10 * @author Cay Horstmann */ public class DialogTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { DialogFrame frame = new DialogFrame(); frame.setTitle("DialogTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package dialog; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; /** * A frame with a menu whose File->About action shows a dialog. */ public class DialogFrame extends JFrame { private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; private AboutDialog dialog; public DialogFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // construct a File menu JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); // add About and Exit menu items // the About item shows the About dialog JMenuItem aboutItem = new JMenuItem("About"); aboutItem.addActionListener(event -> { if (dialog == null) // first time dialog = new AboutDialog(DialogFrame.this); dialog.setVisible(true); // pop up dialog }); fileMenu.add(aboutItem); // the Exit item exits the program JMenuItem exitItem = new JMenuItem("Exit"); exitItem.addActionListener(event -> System.exit(0)); fileMenu.add(exitItem); } }
package dialog; import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; /** * A sample modal dialog that displays a message and waits for the user to click * the OK button. */ public class AboutDialog extends JDialog { public AboutDialog(JFrame owner) { super(owner, "About DialogTest", true); // add HTML label to center add( new JLabel( "<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"), BorderLayout.CENTER); // OK button closes the dialog JButton ok = new JButton("OK"); ok.addActionListener(event -> setVisible(false)); // add OK button to southern border JPanel panel = new JPanel(); panel.add(ok); add(panel, BorderLayout.SOUTH); pack(); } }
运行结果:
测试程序5
l 在elipse IDE中调试运行教材556页程序12-19、12-20,结合运行结果理解程序;
l 掌握对话框的数据交换用法;
l 记录示例代码阅读理解中存在的问题与疑惑。
代码如下:
package dataExchange; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * A frame with a menu whose File->Connect action shows a password dialog. */ public class DataExchangeFrame extends JFrame { public static final int TEXT_ROWS = 20; public static final int TEXT_COLUMNS = 40; private PasswordChooser dialog = null; private JTextArea textArea; public DataExchangeFrame() { // construct a File menu JMenuBar mbar = new JMenuBar(); setJMenuBar(mbar); JMenu fileMenu = new JMenu("File"); mbar.add(fileMenu); // add Connect and Exit menu items JMenuItem connectItem = new JMenuItem("Connect"); connectItem.addActionListener(new ConnectAction()); fileMenu.add(connectItem); // the Exit item exits the program JMenuItem exitItem = new JMenuItem("Exit"); exitItem.addActionListener(event -> System.exit(0)); fileMenu.add(exitItem); textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS); add(new JScrollPane(textArea), BorderLayout.CENTER); pack(); } /** * The Connect action pops up the password dialog. */ private class ConnectAction implements ActionListener { public void actionPerformed(ActionEvent event) { // if first time, construct dialog if (dialog == null) dialog = new PasswordChooser(); // set default values dialog.setUser(new User("yourname", null)); // pop up dialog if (dialog.showDialog(DataExchangeFrame.this, "Connect")) { // if accepted, retrieve user input User u = dialog.getUser(); textArea.append("user name = " + u.getName() + ", password = " + (new String(u.getPassword())) + "\n"); } } } }
package dataExchange; import java.awt.*; import javax.swing.*; /** * @version 1.35 2018-04-10 * @author Cay Horstmann */ public class DataExchangeTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { DataExchangeFrame frame = new DataExchangeFrame(); frame.setTitle("DataExchangeTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package dataExchange; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Frame; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingUtilities; /** * A password chooser that is shown inside a dialog. */ public class PasswordChooser extends JPanel { private JTextField username; private JPasswordField password; private JButton okButton; private boolean ok; private JDialog dialog; public PasswordChooser() { setLayout(new BorderLayout()); // construct a panel with user name and password fields JPanel panel = new JPanel(); panel.setLayout(new GridLayout(2, 2)); panel.add(new JLabel("User name:")); panel.add(username = new JTextField("")); panel.add(new JLabel("Password:")); panel.add(password = new JPasswordField("")); add(panel, BorderLayout.CENTER); // create Ok and Cancel buttons that terminate the dialog okButton = new JButton("Ok"); okButton.addActionListener(event -> { ok = true; dialog.setVisible(false); }); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(event -> dialog.setVisible(false)); // add buttons to southern border JPanel buttonPanel = new JPanel(); buttonPanel.add(okButton); buttonPanel.add(cancelButton); add(buttonPanel, BorderLayout.SOUTH); } /** * Sets the dialog defaults. * @param u the default user information */ public void setUser(User u) { username.setText(u.getName()); } /** * Gets the dialog entries. * @return a User object whose state represents the dialog entries */ public User getUser() { return new User(username.getText(), password.getPassword()); } /** * Show the chooser panel in a dialog. * @param parent a component in the owner frame or null * @param title the dialog window title */ public boolean showDialog(Component parent, String title) { ok = false; // locate the owner frame Frame owner = null; if (parent instanceof Frame) owner = (Frame) parent; else owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent); // if first time, or if owner has changed, make new dialog if (dialog == null || dialog.getOwner() != owner) { dialog = new JDialog(owner, true); dialog.add(this); dialog.getRootPane().setDefaultButton(okButton); dialog.pack(); } // set title and show dialog dialog.setTitle(title); dialog.setVisible(true); return ok; } }
package dataExchange; /** * A user has a name and password. For security reasons, the password is stored as a char[], not a * String. */ public class User { private String name; private char[] password; public User(String aName, char[] aPassword) { name = aName; password = aPassword; } public String getName() { return name; } public char[] getPassword() { return password; } public void setName(String aName) { name = aName; } public void setPassword(char[] aPassword) { password = aPassword; } }
程序的运行结果:
测试程序6
l 在elipse IDE中调试运行教材564页程序12-21、12-22、12-23,结合程序运行结果理解程序;
l 掌握文件对话框的用法;
l 记录示例代码阅读理解中存在的问题与疑惑。
代码如下:
package fileChooser; import java.awt.*; import java.io.*; import javax.swing.*; /** * A file chooser accessory that previews images. */ public class ImagePreviewer extends JLabel { /** * Constructs an ImagePreviewer. * @param chooser the file chooser whose property changes trigger an image * change in this previewer */ public ImagePreviewer(JFileChooser chooser) { setPreferredSize(new Dimension(100, 100)); setBorder(BorderFactory.createEtchedBorder()); chooser.addPropertyChangeListener(event -> { if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) { // 用户选择一个新文件 File f = (File) event.getNewValue(); if (f == null) { setIcon(null); return; } // 将影像读取成图示 ImageIcon icon = new ImageIcon(f.getPath()); // 如果图标太大,无法安装,请缩放 if (icon.getIconWidth() > getWidth()) icon = new ImageIcon(icon.getImage().getScaledInstance( getWidth(), -1, Image.SCALE_DEFAULT)); setIcon(icon); } }); } }
package fileChooser; import java.io.*; import javax.swing.*; import javax.swing.filechooser.*; import javax.swing.filechooser.FileFilter; /** * A frame that has a menu for loading an image and a display area for the * loaded image. */ public class ImageViewerFrame extends JFrame { private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 400; private JLabel label; private JFileChooser chooser; public ImageViewerFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // 设置菜单栏 JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu menu = new JMenu("File"); menuBar.add(menu); JMenuItem openItem = new JMenuItem("Open"); menu.add(openItem); openItem.addActionListener(event -> { chooser.setCurrentDirectory(new File(".")); // 显示文件选择器对话框 int result = chooser.showOpenDialog(ImageViewerFrame.this); // 如果图像文件被接受,将其设置为标签的图标 if (result == JFileChooser.APPROVE_OPTION) { String name = chooser.getSelectedFile().getPath(); label.setIcon(new ImageIcon(name)); pack(); } }); JMenuItem exitItem = new JMenuItem("Exit"); menu.add(exitItem); exitItem.addActionListener(event -> System.exit(0)); // 使用标签显示影像 label = new JLabel(); add(label); //设置文件选择器 chooser = new JFileChooser(); // 接受所有以之结尾的影像档案。JPG。杰伯图形交换格式 FileNameExtensionFilter filter = new FileNameExtensionFilter( "Image files", "jpg", "jpeg", "gif"); chooser.setFileFilter(filter); chooser.setAccessory(new ImagePreviewer(chooser)); chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif"))); } }
package fileChooser; import java.io.*; import javax.swing.*; import javax.swing.filechooser.*; import javax.swing.filechooser.FileFilter; /** * A file view that displays an icon for all files that match a file filter. */ public class FileIconView extends FileView { private FileFilter filter; private Icon icon; /** * Constructs a FileIconView. * @param aFilter a file filter--all files that this filter accepts will be shown * with the icon. * @param anIcon--the icon shown with all accepted files. */ public FileIconView(FileFilter aFilter, Icon anIcon) { filter = aFilter; icon = anIcon; } public Icon getIcon(File f) { if (!f.isDirectory() && filter.accept(f)) return icon; else return null; } }
package fileChooser; import java.awt.*; import javax.swing.*; /** * @version 1.26 2018-04-10 * @author Cay Horstmann */ public class FileChooserTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { ImageViewerFrame frame = new ImageViewerFrame(); frame.setTitle("FileChooserTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
程序的运行结果如下:
实验1:测试程序7
l 在elipse IDE中调试运行教材570页程序12-24,结合运行结果理解程序;
l 了解颜色选择器的用法。
l 记录示例代码阅读理解中存在的问题与疑惑。
具体代码如下:
package colorChooser;
import java.awt.*;
import javax.swing.*;
/**
* @version 1.04 2015-06-12
* @author Cay Horstmann
*/
public class ColorChooserTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new ColorChooserFrame();
frame.setTitle("ColorChooserTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package colorChooser;
import javax.swing.*;
/**
* A frame with a color chooser panel
*/
public class ColorChooserFrame extends JFrame
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public ColorChooserFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);//固定大小
ColorChooserPanel panel = new ColorChooserPanel();
add(panel);
}
}
package colorChooser;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JPanel;
/**
* A panel with buttons to pop up three types of color choosers
*/
public class ColorChooserPanel extends JPanel
{
public ColorChooserPanel()
{
JButton modalButton = new JButton("Modal");
modalButton.addActionListener(new ModalListener());
add(modalButton);
JButton modelessButton = new JButton("Modeless");
modelessButton.addActionListener(new ModelessListener());
add(modelessButton);
JButton immediateButton = new JButton("Immediate");
immediateButton.addActionListener(new ImmediateListener());
add(immediateButton);
}
/**
* This listener pops up a modal color chooser
*/
private class ModalListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Color defaultColor = getBackground();
Color selected = JColorChooser.showDialog(ColorChooserPanel.this, "Set background",
defaultColor);
if (selected != null) setBackground(selected);
}
}
/**
* This listener pops up a modeless color chooser. The panel color is changed when the user
* clicks the OK button.
*/
private class ModelessListener implements ActionListener//实现接口
{
private JDialog dialog;//对话框
private JColorChooser chooser;
public ModelessListener()
{
chooser = new JColorChooser();
dialog = JColorChooser.createDialog(ColorChooserPanel.this, "Background Color",
false /* not modal */, chooser,
event -> setBackground(chooser.getColor()),//getColor()设置颜色
null /* no Cancel button listener */);
}//不太理解
public void actionPerformed(ActionEvent event)
{
chooser.setColor(getBackground());
dialog.setVisible(true);
}
}
/**
* This listener pops up a modeless color chooser. The panel color is changed immediately when
* the user picks a new color.
*/
private class ImmediateListener implements ActionListener
{
private JDialog dialog;
private JColorChooser chooser;
public ImmediateListener()
{
chooser = new JColorChooser();
chooser.getSelectionModel().addChangeListener(
event -> setBackground(chooser.getColor()));
dialog = new JDialog((Frame) null, false /* not modal */);
dialog.add(chooser);
dialog.pack();
}
public void actionPerformed(ActionEvent event)
{
chooser.setColor(getBackground());
dialog.setVisible(true);
}
}
}
运行结果如下:
实验总结:
这一周学习了菜单和对话框及API的相关知识,在理论课上老师也对知识点做了相关讲解。实验都有很多相同和类似的地方,在实验过程中任然没有理解的太清楚。尤其在完成老师留的结对编程设计作业的过程中会遇到更多的问题,心里想的和做出来的往往差距很大。当然,这还是源于自己学习到和真正感受到的知识太少,所以以后我会更加用心地学习。