201871010135 张玉晶《面向对象程序设计(java)》第十五周学习总结
项目 |
内容 |
这个作业属于哪个课程 |
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:
掌握菜单的创建、菜单事件监听器、复选框和单选按钮菜单项、弹出菜单以及快捷键和加速器的用法。
- 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 = ;
- private static final int DEFAULT_HEIGHT = ;
- 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"));
- // 演示加速器
- JMenuItem openItem = fileMenu.add(new TestAction("Open")); //
- openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O")); //将加速器ctrl O关联到openItem菜单项
- fileMenu.addSeparator(); //在fileMenu菜单中添加分隔符
- saveAction = new TestAction("Save");
- JMenuItem saveItem = fileMenu.add(saveAction);
- saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S")); //将加速器ctrl S关联到saveItem菜单项
- saveAsAction = new TestAction("Save As");
- fileMenu.add(saveAsAction);
- fileMenu.addSeparator();
- fileMenu.add(new AbstractAction("Exit")
- {
- public void actionPerformed(ActionEvent event)
- {
- System.exit();
- }
- });
- // 演示复选框和单选按钮菜单
- readonlyItem = new JCheckBoxMenuItem("Read-only"); //用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);//把insertItem对象加到按钮组中
- group.add(overtypeItem);
- // 演示图标
- 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);
- // 演示嵌套菜单
- JMenu optionMenu = new JMenu("Options");
- optionMenu.add(readonlyItem);
- optionMenu.addSeparator();
- optionMenu.add(insertItem);
- optionMenu.add(overtypeItem);
- editMenu.addSeparator();
- editMenu.add(optionMenu);//把optionMenu菜单嵌套在edit菜单中
- // 演示助记符
- JMenu helpMenu = new JMenu("Help");
- helpMenu.setMnemonic('H'); //为Help这个菜单设置快捷键H
- JMenuItem indexItem = new JMenuItem("Index");
- indexItem.setMnemonic('I'); //为Help这个菜单设置快捷键I
- helpMenu.add(indexItem);//将Index菜单项添加到Help这个菜单中
- //也可以将助记键添加到动作中
- TestAction aboutAction = new TestAction("About");
- aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A')); //为aboutAction对象添加快捷键A
- helpMenu.add(aboutAction);
- // 将所有顶级菜单添加到菜单栏
- JMenuBar menuBar = new JMenuBar();//创建一个菜单栏
- setJMenuBar(menuBar);
- menuBar.add(fileMenu);
- menuBar.add(editMenu);
- menuBar.add(helpMenu);
- // 演示弹出窗口
- popup = new JPopupMenu(); //创建一个弹出菜单
- popup.add(cutAction);
- popup.add(copyAction);
- popup.add(pasteAction);
- JPanel panel = new JPanel();
- panel.setComponentPopupMenu(popup); //用户点击panel时弹出菜单
- add(panel);
- }
- }
- 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);
- });
- }
- }
运行结果如下:
测试程序2:
掌握工具栏和工具提示的用法
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- /**
- * 带有工具栏和颜色变化菜单的框架
- */
- public class ToolBarFrame extends JFrame
- {
- private static final int DEFAULT_WIDTH = ;
- private static final int DEFAULT_HEIGHT = ;
- private JPanel panel;
- public ToolBarFrame()
- {
- setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
- // 添加用于颜色更改的面板
- panel = new JPanel();
- add(panel, BorderLayout.CENTER);//将这个面板加在边框的中间
- // 设置操作
- 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();
- }
- };
- exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");
- // 填充工具栏
- JToolBar bar = new JToolBar(); //创建一个工具栏
- bar.add(blueAction);
- bar.add(yellowAction);
- bar.add(redAction);
- bar.addSeparator(); //给工具栏添加分隔符
- bar.add(exitAction);
- add(bar, BorderLayout.NORTH);
- //填充菜单
- 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);
- }
- /**
- * 颜色动作将框架的背景设置为给定的颜色.
- */
- 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); //给面板加背景
- }
- }
- }
- 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);
- });
- }
- }
运行结果如下:
测试程序3:
掌握选项对话框的用法
- import java.awt.*;
- import java.awt.event.*;
- import java.awt.geom.*;
- import java.awt.geom.Rectangle2D.Double;
- import java.util.*;
- import javax.swing.*;
- /**
- * 包含用于选择各种选项对话框的设置的框架。
- */
- 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);
- // 添加带有显示按钮的面板
- 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 -;
- }
- }
- /**
- * 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()[]);
- }
- }
- }
- /**
- * A component with a painted surface
- */
- class SampleComponent extends JComponent
- {
- public void paintComponent(Graphics g)
- {
- Graphics2D g2 = (Graphics2D) g;
- Double rect = new Rectangle2D.Double(, , getWidth() - , getHeight() - );
- g2.setPaint(Color.YELLOW);
- g2.fill(rect);
- g2.setPaint(Color.BLUE);
- g2.draw(rect);
- }
- public Dimension getPreferredSize()
- {
- return new Dimension(, );
- }
- }
- 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();
- // 为每个选项制作一个单选按钮
- for (String option : options)
- {
- JRadioButton button = new JRadioButton(option);
- button.setActionCommand(option);
- add(button);
- group.add(button);
- button.setSelected(option == options[]);
- }
- }
- /**
- * Gets the currently selected option.
- * @return the label of the currently selected radio button.
- */
- public String getSelection()
- {
- return group.getSelection().getActionCommand();
- }
- }
- 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);
- });
- }
- }
运行结果如下:
测试程序4:
掌握对话框的创建方法
- 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 = ;
- private static final int DEFAULT_HEIGHT = ;
- private AboutDialog dialog;
- public DialogFrame()
- {
- setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
- // 构造文件菜单
- JMenuBar menuBar = new JMenuBar();//创建一个菜单栏
- setJMenuBar(menuBar);
- JMenu fileMenu = new JMenu("File");
- menuBar.add(fileMenu);//将File菜单添加到菜单栏上
- // 添加和退出菜单项
- // About项目显示About对话框
- JMenuItem aboutItem = new JMenuItem("About");
- aboutItem.addActionListener(event -> {
- if (dialog == null) // first time
- dialog = new AboutDialog(DialogFrame.this);
- dialog.setVisible(true); // 弹出对话框
- });
- fileMenu.add(aboutItem);
- // 退出项目退出程序
- JMenuItem exitItem = new JMenuItem("Exit");
- exitItem.addActionListener(event -> System.exit());
- fileMenu.add(exitItem);//将菜单项添加到菜单上
- }
- }
- 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);
- });
- }
- }
- 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);
- //将html标签添加到中心
- add(
- new JLabel(
- "<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"),
- BorderLayout.CENTER);
- // ok按钮关闭对话框
- JButton ok = new JButton("OK");
- ok.addActionListener(event -> setVisible(false));
- // 将“ok”按钮添加到南部边框
- JPanel panel = new JPanel();
- panel.add(ok);
- add(panel, BorderLayout.SOUTH);
- pack();
- }
- }
运行结果如下:
测试程序5:
掌握对话框的数据交换用法;
- 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 = ;
- public static final int TEXT_COLUMNS = ;
- private PasswordChooser dialog = null;
- private JTextArea textArea;
- public DataExchangeFrame()
- {
- // 构建文件菜单
- JMenuBar mbar = new JMenuBar();//创建一个菜单栏
- setJMenuBar(mbar);
- JMenu fileMenu = new JMenu("File"); //创建一个菜单
- mbar.add(fileMenu);//在菜单栏中添加菜单
- // 添加连接和退出菜单项
- JMenuItem connectItem = new JMenuItem("Connect");//创建一个菜单项
- connectItem.addActionListener(new ConnectAction());
- fileMenu.add(connectItem);//将菜单项添加到菜单
- // Exit项目退出程序
- JMenuItem exitItem = new JMenuItem("Exit");
- exitItem.addActionListener(event -> System.exit());
- 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 (dialog == null) dialog = new PasswordChooser();
- // 设置默认值
- dialog.setUser(new User("yourname", null));
- // 弹出对话框
- if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
- {
- // 如果接受,检索用户输入
- User u = dialog.getUser();
- textArea.append("user name = " + u.getName() + ", password = "
- + (new String(u.getPassword())) + "\n");
- }
- }
- }
- }
- 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);
- });
- }
- }
- 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());
- // 构建一个包含用户名和密码字段的面板
- 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);//将该面板添加到边框的中间
- // 创建终止对话框的“确定”和“取消”按钮
- okButton = new JButton("Ok");
- okButton.addActionListener(event -> {
- ok = true;
- dialog.setVisible(false);
- });
- JButton cancelButton = new JButton("Cancel");
- cancelButton.addActionListener(event -> dialog.setVisible(false));
- // 向南部边框添加按钮
- 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;
- // 定位到owner 框架
- Frame owner = null;
- if (parent instanceof Frame)
- owner = (Frame) parent;
- else
- owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
- //如果是第一次,或者owner已经更改,请创建新对话框
- if (dialog == null || dialog.getOwner() != owner)
- {
- dialog = new JDialog(owner, true);
- dialog.add(this);
- dialog.getRootPane().setDefaultButton(okButton);
- dialog.pack();
- }
- // 设置标题和显示对话框
- dialog.setTitle(title);
- dialog.setVisible(true);
- return ok;
- }
- }
- /**
- * 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:
掌握文件对话框的用法
- 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 = ;
- private static final int DEFAULT_HEIGHT = ;
- 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());
- // 使用标签显示图像
- label = new JLabel();
- add(label);
- // 设置文件选择器
- chooser = new JFileChooser();
- // 接受所有以jpg,jpeg ,gif结尾的图像文件
- 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")));
- }
- }
- 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(, ));
- 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(), -, Image.SCALE_DEFAULT));
- setIcon(icon);
- }
- });
- }
- }
- import java.io.*;
- import javax.swing.*;
- import javax.swing.filechooser.*;
- import javax.swing.filechooser.FileFilter;
- /**
- *显示与文件过滤器匹配的所有文件的图标的文件视图。
- */
- 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;
- }
- }
- 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);
- });
- }
- }
运行结果如下:
测试程序7:
了解颜色选择器的用法
- package 第十五周;
- import javax.swing.*;
- /**
- * A frame with a color chooser panel
- */
- public class ColorChooserFrame extends JFrame
- {
- private static final int DEFAULT_WIDTH = ; //两个私有属性,常量
- private static final int DEFAULT_HEIGHT = ;
- public ColorChooserFrame() //ColorChooserFrame构造器
- {
- setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); //设置为两个常量大小的框架
- // add color chooser panel to frame
- ColorChooserPanel panel = new ColorChooserPanel(); //创建一个ColorChooserPanel类对象panel
- add(panel); //将panel添加到框架里面
- }
- }
- package 第十五周;
- 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() //ColorChooserPanel构造器
- {
- JButton modalButton = new JButton("Modal"); //创建一个JButton按钮对象
- modalButton.addActionListener(new ModalListener()); //动作监听器对象
- add(modalButton); //将JButton对象添加到框架里面
- JButton modelessButton = new JButton("Modeless"); //新建一个Modeless按钮
- modelessButton.addActionListener(new ModelessListener()); //添加动作监听器
- add(modelessButton); //将按钮添加到框架当中
- JButton immediateButton = new JButton("Immediate"); //新建一个Immediate按钮
- immediateButton.addActionListener(new ImmediateListener()); //添加动作监听器
- add(immediateButton); //将immediateButton添加到框架当中
- }
- /**
- * This listener pops up a modal color chooser
- */
- private class ModalListener implements ActionListener //创建一个实现ActionListener接口的类ModalListener
- {
- public void actionPerformed(ActionEvent event) //actionPerformed方法
- {
- 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 //ModelessListener类实现了ActionListener接口
- {
- private JDialog dialog; //对话框
- private JColorChooser chooser; //颜色选择器
- public ModelessListener() //ModelessListener构造器
- {
- chooser = new JColorChooser(); //创建一个JColorChooser选择器类对象
- dialog = JColorChooser.createDialog(ColorChooserPanel.this, "Background Color",
- false /* not modal */, chooser,
- event -> setBackground(chooser.getColor()),
- null /* no Cancel button listener */);
- }//创建一个对话框,颜色选择器面板ColorChooserPanel.this是本类,提供组件。设置背景颜色为颜色选择器调用getColor方法得到的颜色
- public void actionPerformed(ActionEvent event) //actionPerformed方法
- {
- 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 //ImmediateListener是实现ActionListener接口的类
- {
- private JDialog dialog;
- private JColorChooser chooser; //私有属性,颜色选择器的定义
- public ImmediateListener() //ImmediateListener构造器
- {
- chooser = new JColorChooser(); //新建一个颜色选择器类对象
- chooser.getSelectionModel().addChangeListener(
- event -> setBackground(chooser.getColor()));
- dialog = new JDialog((Frame) null, false /* not modal */);
- dialog.add(chooser);//添加chooser到文本框当中
- dialog.pack(); //获取对话框的首选大小
- }
- public void actionPerformed(ActionEvent event)//actionPerformed方法
- {
- chooser.setColor(getBackground()); //设置背景颜色
- dialog.setVisible(true); //设置组件可见
- }
- }
- }
- package 第十五周;
- 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);
- });
- }
- }
运行结果如下:
实验总结:
本周重点学了菜单和对话框,包括在菜单栏上添加菜单项,嵌套菜单,以及弹出菜单的使用,还有对话框的很多类型,有选择对话框,确认对话框,消息对话框,还有确认对话框。本周的实验都是验证性实验,通过看书,注释,网上查找,还有问同学就感觉是懂了点,但是理解的还不是很透彻,我会在课余时间自己看着书多敲几遍,多理解理解。
201871010135 张玉晶《面向对象程序设计(java)》第十五周学习总结的更多相关文章
- 201571030332 扎西平措 《面向对象程序设计Java》第八周学习总结
<面向对象程序设计Java>第八周学习总结 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https: ...
- 201771010118马昕璐《面向对象程序设计java》第八周学习总结
第一部分:理论知识学习部分 1.接口 在Java程序设计语言中,接口不是类,而是对类的一组需求描述,由常量和一组抽象方法组成.Java为了克服单继承的缺点,Java使用了接口,一个类可以实现一个或多个 ...
- 201771010134杨其菊《面向对象程序设计java》第八周学习总结
第八周学习总结 第一部分:理论知识 一.接口.lambda和内部类: Comparator与comparable接口: 1.comparable接口的方法是compareTo,只有一个参数:comp ...
- 201771010134杨其菊《面向对象程序设计java》第七周学习总结
第七周学习总结 第一部分:理论知识 1.继承是面向对象程序设计(Object Oriented Programming-OOP)中软件重用的关键技术.继承机制使用已经定义的类作为基础建立新的类定义,新 ...
- 周强201771010141《面向对象程序设计Java》第八周学习总结
一.理论知识学习部分 Java为了克服单继承的缺点,Java使用了接口,一个类可以实现一个或多个接口. 接口体中包含常量定义和方法定义,接口中只进行方法的声明,不提供方法的实现. 类似建立类的继承关系 ...
- 201871010126 王亚涛《面向对象程序设计 JAVA》 第十三周学习总结
内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/ ...
- 201871010126 王亚涛 《面向对象程序设计 (Java)》第十七周学习总结
内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/12 ...
- 马凯军201771010116《面向对象程序设计Java》第八周学习总结
一,理论知识学习部分 6.1.1 接口概念 两种含义:一,Java接口,Java语言中存在的结构,有特定的语法和结构:二,一个类所具有的方法的特征集合,是一种逻辑上的抽象.前者叫做“Java接口”,后 ...
- 201777010217-金云馨《面向对象程序设计Java》第八周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- 201871010135 张玉晶《面向对象程序设计(java)》第七周学习总结
201871010135 张玉晶<面向对象程序设计(java)>第七周学习总结 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ ...
随机推荐
- day52_9_16Django中的静态文件和orm
一.静态文件配置 在配置静态文件时,需要创建一个文件夹在Django项目文件夹下,名字与使用无关. 静态文件包括html等使用的不会变动的插件文件等.分为三个部分: css文件夹 当前网站所有的样式文 ...
- CloudCompare中对点云进行降采样和剪裁
降采样: Edit=>Subsample 出现一个弹窗,可以选择3种降采样的方式:Random, Space, Octree. 下面用一个例子来说明3种方式.例子是一个5.88M个点的点云文件( ...
- LeetCode98. 验证二叉搜索树
验证二叉搜索树 * * https://leetcode-cn.com/problems/validate-binary-search-tree/description/ * * algor ...
- tcp 和UDP
文章目录前言1. UDP2. TCP2.1 TCP 的三次握手2.2 TCP 四次挥手2.3 累计确认2.4 顺序问题和丢包问题2.5 流量控制的问题2.6 拥塞控制的问题总结及面试问题前言前端的 ...
- 安装Rtools
1.好多工具需要安装Rtools install.packages("installr") install.packages("stringr") ###依赖包 ...
- 10.python3实用编程技巧进阶(五)
5.1.如何派生内置不可变类型并修其改实例化行为 修改实例化行为 # 5.1.如何派生内置不可变类型并修其改实例化行为 #继承内置tuple, 并实现__new__,在其中修改实例化行为 class ...
- Serializable接口的意义和用法
本人软件工程大三妹子一枚,以下为个人观点仅供参考: 最近在云课堂学习springmvc+mybatis项目时,发现老师在实体类中引用了serializable这个接口,如下: import jav ...
- Python 学习 第15篇:日期和时间
datetime模块中包含五种基本类型:date.time.datetime.timedelta和tzinfo,tz是time zone的缩写,tzinfo用于表示时区信息. 一,date类型 dat ...
- 搭建 Frp 来远程内网 Windows 和 Linux 机子
魏刘宏 2019 年 5 月 19 日 一.使用一键脚本搭建服务端 Frp 这个内网穿透项目的官方地址为 https://github.com/fatedier/frp ,不过我们今天搭建服务端时不直 ...
- 如何搭建wordpress ,wecenter
14.什么是LNMP架构 LNMP是指一组通常一起使用来运行动态网站或者服务器的自由软件名称首字母缩写.L指Linux,N指Nginx,M一般指MySQL,也可以指MariaDB,P一般指PHP,也可 ...