201871010113-刘兴瑞《面向对象程序设计(java)》第十五周学习总结
项目 |
内容 |
这个作业属于哪个课程 |
<任课教师博客主页链接>https://www.cnblogs.com/nwnu-daizh/ |
这个作业的要求在哪里 |
<作业链接地址>https://www.cnblogs.com/nwnu-daizh/p/11995615.htmll |
作业学习目标 |
(1)掌握GUI布局管理器用法; (2)掌握Java Swing文本输入组件用途及常用API; (3)掌握Java Swing选择输入组件用途及常用API。
|
第一部分:总结菜单、对话框两类组件用途及常用API
菜单:
1.JMenuBar 菜单栏
菜单栏是窗口中用于容纳菜单JMenu的容器。 JFrame对象可以调用setJMenuBar()方法将一个菜单栏实例menubar添加到容器中,作为整个菜单树的根基。菜单栏被添加到窗口的上方,不受布局管理器控制。
注意:只能向窗口中添加一个菜单栏。
public JMenuBar(){ //默认构造方法,创建新的菜单栏 } public JMenu add(JMenu c){ //将菜单追加到菜单栏末尾 }
2.JMenu 菜单
菜单是若干个菜单项(JMenuItem)或子菜单的容器,它能被添加到JMenuBar或其他JMenu中。
public JMenu(){ //默认构造方法,创建没有文本的新菜单 } public JMenu(String s){ //构造方法,用提供的字符串作为文本构造一个新菜单 } public Component add(Component c){ //将某个组件追加到此菜单的末尾 } public JMenuItem add(JMenuItem c){ //将某个菜单项追加到此菜单的末尾 } public void addSeparator(){ //将新分隔符追加到菜单的末尾 }
3.JMenuItem 菜单项
菜单项是组成菜单或快捷键的最小单位,用于完成特定功能。
public JMenuItem(){ //默认构造方法,创建不带文本或图标的菜单项 } public JMenuItem(String text){ //构造方法 } public void setAccelerator(KeyStroke keystroke){ //为菜单项设置快捷键 }
4.选择菜单项
Java除了提供JMenuItem,还提供了两种可选择的菜单项:复选菜单项(JCheckBoxMenuItem)和单选菜单项(JRadioButtonMenuItem)。
5.JPopupMenu 快捷菜单项
菜单除了可以放置在窗口,也可以依附于一个组件,当用户右击鼠标时弹出
public JPopupMenu(){ //默认构造方法 } public JPopupMenu(String s) //构造方法,具有指定标题 } public JMenuItem add(JMenuItem jm){ //将指定菜单项添加到此菜单的末尾 } public void addSeparator(){ //将新分隔符追加到菜单的末尾 }
对话框:
1、对话框模式
对话框分为无模式和有模式两种。
如果一个对话框是有模式的,那么当这个对话框处于激活状态时,只让程序响应对话框内部的事件,而且将堵塞其它线程的执行,用户不能再激活对话框所在程序中的其它窗口,直到该对话框消失不可见。
无模式对话框处于激活状态时,能再激活其它窗口,也不堵塞其它线程执行。
3、文件对话框(FileDialog)
文件对话框是一个从文件中选择文件的界面,文件对话框事实上并不能打开或保存文件,它只能得到要打开或保存的文件的名字或所在的目录,要想真正实现打开或保存文件,还必须使用输入、输出流。
javax.swing包中的JFileChooser类可以创建文件对话框,使用该类的构造方法JFileChooser()创建初始不可见的有模式的文件对话框。showSaveDialog(Component a), showOpenDialog(Component a)都可使得对话框可见,但外观有所不同。showSaveDialog(Component a)方法提供保存文件的界面,showOpenDialog(Component a)方法提供打开文件的界面。参数a指定对话框可见时的位置。
当用户单击文件对话框上的“确定”、“取消”按键或关闭图标,文件对话框将消失,方法返回:JFileChooser.APPROVE_OPTION和JFileChooser.CANCEL_OPTION之一。当返回值是JFileChooser.APPROVE_OPTION时,可以使用JFileChooser类的getSelectedFile()得到文件对话框所选择的文件。
FileDialog是Dialog的子类,主要方法有:
1、FileDialog(Frame f,String s,int mode):构造方法,f为所依赖的窗口对象,s是对话框的名字,mode取值为FileDialog.LOAD或FileDialog.SAVE。
2、public String getDirwctory():获取当前对话框中所显示的文件目录。
3、public String getFile():获取对话框中显示的文件的字符串表示,如不存在则为null。
4、消息对话框
消息对话框是有模式对话框,进行一个重要的操作动作之前,弹出一个消息对话框。可以用javax.swing包中的JOptionPane类的静态方法。
public static void showMessageDialog(Component parentComponent,String message, String title, int messageType); Component parentComponent://消息对话框依赖的组件 String message:// 要显示的消息 String title://对话框的标题 int messageType)://对话框的外观,取值如下: JOptionPane.INFORMATION_MESSAGE JOptionPane.WARNING_MESSAGE JOptionPane.ERROR_MESSAGE JOptionPane.QUESTION_MESSAGE JOptionPane.PLAIN_MESSAGE
5、输入对话框
输入对话框含有供用户输入文本的文本框、一个“确定”和“取消”按钮,是有模式对话框。当输入对话框可见时,要求用户输入一个字符串。javax.swing包中的JOptionPane类静态方法:
public static String showInputDialog(Component parentComponent, Object message, String title, int messageType); Component parentComponent//指定输入对话框所依赖的组件。 Object message//指定对话框上的提示信息。 String title//对话框上的标题。 int messageType//确定对话框的外观,取值如下: ERROR_MESSAGE INFORMATION_MESSAGE WARNING_MESSAGE QUESTION_MESSAGE PLAIN_MESSAGE
6、确认对话框
确认对话框是有模式对话框,可以用javax.swing包中的JOptionPane类的静态方法创建:
public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType); Component parentComponent //对话框所依赖的组件。 Object messag //对话框上显示的消息 String titl //对话框的标题 int optionType //对话框的外观,取值如下: JOptionPane.YES_NO_OPTION JOptionPane.YES_NO_CANCEL_OPTION JOptionPane.OK_CANCEL_OPTION
当对话框消失后,showConfirmDialog方法会返回下列整数之一:
JOptionPane.YES_OPTION
JOptionPane.NO_OPTION
JOptionPane.CANCEL_OPTION
JOptionPane.OK_OPTION
JOptionPane.CLOSED_OPTION
7、颜色对话框
使用java.swing包中的JColorChooser类表静态方法创建:
public static Color showDialog(Component component,String title,Color initialColor); Component component//对话框所依赖的组件。 String title//对话框的标题。 Color initialColor)//对话框消失后返回的默认颜色
第二部分:实验部分
1、实验目的与要求
(1) 掌握菜单组件用途及常用API;
(2) 掌握对话框组件用途及常用API;
(3) 学习设计简单应用程序的GUI。
2、实验内容和步骤
实验1: 导入第12章示例程序,测试程序并进行组内讨论。
测试程序1
l 在elipse IDE中调试运行教材512页程序12-8,结合运行结果理解程序;
l 掌握菜单的创建、菜单事件监听器、复选框和单选按钮菜单项、弹出菜单以及快捷键和加速器的用法。
l 记录示例代码阅读理解中存在的问题与疑惑。
代码如下:
MenuTest.java:
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(() -> { var frame = new MenuFrame(); frame.setTitle("MenuTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
MenuFrame.java:
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); var fileMenu = new JMenu("File");//构建菜单 fileMenu.add(new TestAction("New")); // demonstrate accelerators var 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(); //采用扩展抽象类AbstractAction来定义一个实现Action接口的类 fileMenu.add(new AbstractAction("Exit") { /** * */ private static final long serialVersionUID = 1L; //指定菜单项标签并且覆盖actionPerformed方法来获得菜单动作处理器 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); } }); /* * 复选框和单选按钮菜单项 */ var group = new ButtonGroup(); var insertItem = new JRadioButtonMenuItem("Insert");//构造单选钮菜单项 insertItem.setSelected(true); var overtypeItem = new JRadioButtonMenuItem("Overtype"); group.add(insertItem); group.add(overtypeItem); // demonstrate icons var cutAction = new TestAction("Cut"); cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif")); var copyAction = new TestAction("Copy"); copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif")); var pasteAction = new TestAction("Paste"); pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif")); var editMenu = new JMenu("Edit"); editMenu.add(cutAction); editMenu.add(copyAction); editMenu.add(pasteAction); // demonstrate nested menus var optionMenu = new JMenu("Options"); optionMenu.add(readonlyItem); optionMenu.addSeparator(); optionMenu.add(insertItem); optionMenu.add(overtypeItem); editMenu.addSeparator(); editMenu.add(optionMenu); // demonstrate mnemonics //调用setMnemonic方法,为菜单设置快捷键 var helpMenu = new JMenu("Help"); helpMenu.setMnemonic('H'); var indexItem = new JMenuItem("Index"); indexItem.setMnemonic('I'); helpMenu.add(indexItem); // you can also add the mnemonic key to an action var aboutAction = new TestAction("About"); aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A')); helpMenu.add(aboutAction); // add all top-level menus to menu bar //创建菜单栏 var 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); var panel = new JPanel(); panel.setComponentPopupMenu(popup); add(panel); } }
运行结果如图:
小结:位于窗口顶部的菜单栏包括了下拉菜单的名字。点击一个名字就可以打开包含菜单项和子菜单的菜单。当用户点击菜单项时,所有的菜单都会被关闭并且将一条消息发送给程序。
测试程序2
l 在elipse IDE中调试运行教材517页程序12-9,结合运行结果理解程序;
l 掌握工具栏和工具提示的用法;
l 记录示例代码阅读理解中存在的问题与疑惑。
程序代码如下:
ToolBarTest.java:
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(() -> { var frame = new ToolBarFrame(); frame.setTitle("ToolBarTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
ToolBarFrame.java:
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 var blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE); var yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),Color.YELLOW); var redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); var exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif")) { public void actionPerformed(ActionEvent event) { System.exit(0); } }; exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit"); // populate toolbar //创建工具栏 var bar = new JToolBar(); bar.add(blueAction); bar.add(yellowAction); bar.add(redAction); bar.addSeparator();//添加分隔符 bar.add(exitAction); add(bar, BorderLayout.NORTH);//将工具栏添加到框架中 // populate menu var menu = new JMenu("Color"); menu.add(yellowAction); menu.add(blueAction); menu.add(redAction); menu.add(exitAction); var 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 记录示例代码阅读理解中存在的问题与疑惑。
程序代码如下:
OptionDialogTest.Java:
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(() -> { var frame = new OptionDialogFrame(); frame.setTitle("OptionDialogTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
OptionDialogFrame.java:
package optionDialog; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; 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() { //创建一个面板,设置为两行三列的网格,每个网格中定义一个单选的面板 var 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 //创建一个按钮组件,设置监听事件 var showPanel = new JPanel(); var 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) { var g2 = (Graphics2D) g; var 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); } }
ButtonPanel.java:
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) { var 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(); } }
运行结果如图:
小结:简单的对话框,用于获取用户的一些简单信息。输入对话框用于接受用户输入的额外组件。选项包括:1:选择对话框的类型,2:选择图标,3;选择消息,4:对于确认对话框,选择选项类型,5;对于选项对话框,选择选项,6:调用JOptionPane API中的相应方法。
测试程序4
l 在elipse IDE中调试运行教材552页程序12-17、12-18,结合运行结果理解程序;
l 掌握对话框的创建方法;
l 记录示例代码阅读理解中存在的问题与疑惑。
程序代码如下:
DialogTest.java:
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(() -> { var frame = new DialogFrame(); frame.setTitle("DialogTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
DialogFrame.java:
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 var menuBar = new JMenuBar(); setJMenuBar(menuBar); var fileMenu = new JMenu("File"); menuBar.add(fileMenu); // add About and Exit menu items // the About item shows the About dialog var aboutItem = new JMenuItem("About"); //lambda表达式 aboutItem.addActionListener(event -> { if (dialog == null) // first time //建立新的对话框对象,设置可见 dialog = new AboutDialog(DialogFrame.this); dialog.setVisible(true); }); fileMenu.add(aboutItem); // the Exit item exits the program var exitItem = new JMenuItem("Exit"); exitItem.addActionListener(event -> System.exit(0)); fileMenu.add(exitItem); } }
AboutDialog.java:
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 { //调用超类JDialog的构造器 public AboutDialog(JFrame owner) { super(owner, "About DialogTest", true); //添加对话框的用户界面组件 add( new JLabel( "<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"), BorderLayout.CENTER); // OK button closes the dialog //点击OK按钮时,对话框被关闭 var ok = new JButton("OK"); ok.addActionListener(event -> setVisible(false)); // add OK button to southern border var panel = new JPanel(); panel.add(ok); add(panel, BorderLayout.SOUTH); pack(); } }
运行结果如图:
小结:实现一个对话框,需要从JDialog派生一个类。具体过程如下:1:在对话框构造器中调用超类JDialog的构造器,2:添加对话框的用户界面组件,3:添加事件处理器,4;设置对话框的大小。
测试程序5
l 在elipse IDE中调试运行教材556页程序12-19、12-20,结合运行结果理解程序;
l 掌握对话框的数据交换用法;
l 记录示例代码阅读理解中存在的问题与疑惑。
程序代码如下:
DataExchangeTest.java:
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(() -> { var frame = new DataExchangeFrame(); frame.setTitle("DataExchangeTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
DataExchangeFrame.java:
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() { //创建一个菜单 var mbar = new JMenuBar(); setJMenuBar(mbar); var fileMenu = new JMenu("File"); mbar.add(fileMenu); //添加菜单项 var connectItem = new JMenuItem("Connect"); connectItem.addActionListener(new ConnectAction()); fileMenu.add(connectItem); // the Exit item exits the program var 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"); } } } } PasswordChooser.java: 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 var 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); }); var cancelButton = new JButton("Cancel"); cancelButton.addActionListener(event -> dialog.setVisible(false)); // add buttons to southern border var buttonPanel = new JPanel(); buttonPanel.add(okButton); buttonPanel.add(cancelButton); add(buttonPanel, BorderLayout.SOUTH); } /** * Sets the dialog defaults. * @param u the default user information */ //PasswordChooser类提供的setUser方法 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 */ //在showDialog方法中动态建立JDialog对象 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; } }
User.java:
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中调试运行教材556页程序12-21、12-22、12-23,结合程序运行结果理解程序;
l 掌握文件对话框的用法;
l 记录示例代码阅读理解中存在的问题与疑惑。
程序代码如下:
FileChooserTest.java:
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(() -> { var frame = new ImageViewerFrame(); frame.setTitle("FileChooserTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
FileIconView.java:
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; } } ImagePreviewer.java: 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); } }); } } ImageViewerFrame.java: 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图形交换格式 FileFilter 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"))); } }
运行结果如图:
小结:文件对话框,调用showOpenDialog。接受文件的按钮被自动的标签为Open或者Save,也可以调用showDialog方法为按钮设定标签。
测试程序7
l 在elipse IDE中调试运行教材570页程序12-24,结合运行结果理解程序;
l 了解颜色选择器的用法。
l 记录示例代码阅读理解中存在的问题与疑惑。
程序代码如下:
ColorChooserTest.java:
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); }); } }
ColorChooserPane.java:
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 */ //设置了Modal按钮的监听事件 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. */ //设置了Modeless按钮的监听事件 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()), 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. */ //设置了Immediate按钮的监听事件 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); } } }
ColorChooserFrame.java:
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); // add color chooser panel to frame ColorChooserPanel panel = new ColorChooserPanel();//创建一个颜色选择器 add(panel); } }
运行结果如图:
小结:颜色选择器是一个组件,包含了用于创建包含颜色选择器组件的对话框方法。有三种对话框类型。如果点击Model按钮,则需要选择一个颜色才能继续后面的操作。如果点击Modaless按钮,则会得到一个无模式对话框。只有点击OK按钮时,颜色才会发生改变。如果点击Immediate按钮,会得到一个没有按钮的无模式对话框。
3、实验总结:
在学习了十一章的基础上,通过对本章的学习,对用户界面有了更加复杂的设计,使的用户界面更加美观,功能更更加丰富,学习了多种布局方式
(1)FlowLayout: 流布局(Applet和Panel的默认布局管理器)
(2)BorderLayout:边框布局( Window、Frame和Dialog的默认布局管理器)
(3)GridLayout: 网格布局
(4)GridBagLayout: 网格组布局
(5)CardLayout :卡片布局
这一章相对于上一章学习了菜单和对话框的相关知识。
posted on 2019-12-09 18:52 201871010113-刘兴瑞 阅读(202) 评论(1) 编辑 收藏 举报