黎沫

导航

201871010119-帖佼佼《面向对象程序设计(java)》第十五周学习总结

博文正文开头格式:(2分)

项目

内容

这个作业属于哪个课程

 https://www.cnblogs.com/nwnu-daizh/

这个作业的要求在哪里

   https://www.cnblogs.com/nwnu-daizh/p/11435127.html

作业学习目标

(1) 掌握菜单组件用途及常用API;

(2) 掌握对话框组件用途及常用API;

(3) 学习设计简单应用程序的GUI。

随笔博文正文内容包括:

第一部分:总结菜单、对话框两类组件用途及常用API(30分)

 1、菜单简介:菜单时GUI编程中经常用到得一种组件。位于窗口顶部的菜单栏(menu bar)中包括下拉菜单得名字。点击一个名字就可以打开包含菜单项(menu items)和子菜单(submenus)得菜单。

2、菜单得创建:

   (1)创建一个菜单栏:菜单栏是一个可以添加到容器组件任何位置的组件。通常放在框架的顶部;

    JFrameBar menuBar= new  JFrameBar();

   (2)调用框架的setMenuBar方法可将一个菜单栏对象添加到框架上。

    frame.setMenuBar(menuBar);

     (3)创建菜单对象,并将菜单对象添加到菜单栏当中。

    JMenu  editMenu = new JMenu ("Edit");

    menuBar.add(editMenu ;

     (4)向菜单对象中添加一个菜单项:

    JMenuItem  pasteitem = new  JMenuItem();

    editMenu .add(pasteitem );

     (5)向菜单对象添加分隔符:

     editMenu .addSeperator();

     (6)向菜单对象项加入子菜单:

    JMenu  optionMenu = new  JMenu (“option”);

    editMenu .add(optionMenu );

3、菜单事件监听器的插入方法:

   (1)当用户选择菜单时,将触发一个动作事件。这里需要为每一个菜单项安装一个动作监听器。

    ActionListener  listener = 。。。。。。;

    paasteItem.addActionListener(listener);

   (2)弹出菜单(JPopMenu)

    弹出菜单是不固定在菜单栏中随处浮动的菜单;

4、创建弹出菜单:

  (1)创建一个弹出菜单与创建一个常规菜单的方法类似,但是弹出菜单没有标题;

  JPopMenu   popup  =  new  JPopMenu();

  (2)然后用常规方法为弹出菜单添加菜单项:

  JMenuItem  item = new  JMenuItem(“Cut”);

  item.addActionListener(listener);

  popup.add(item);

  (3)弹出菜单调用show方法才能显示出来;

  popup.show(panel,x,y);

5、弹出式触发器:

  (1)弹出式触发器(pop-up  trigger):用户点击鼠标某个键时弹出菜单;

  (2)在Windows或者Linux中,弹出式触发器式鼠标右键;

  (3)要想在用户点击某一个组件的时候弹出菜单,该组件就要调用以下的方法设置弹出式触发器:

  component.setComponentPopupMenu(popup);

6、快捷键:

  (1)可以为菜单项设置快捷键。在当前菜单打开的情况下,可以按下某菜单项的快捷键,相当于鼠标单击了该菜单项;

  JMenuItem  Cutltem = new  JMenuItem("Index");

  CutItem.setMnemonic("!");

  (2)此快捷键就会自动显示在菜单项中,快捷键下面有一条下划线。

7、加速器:

  (1)加速器可以在不打开菜单的情况下选中菜单项的快捷键。例如,很多应用程序把CTRL+O和CTRL+S关联到菜单中的Open和Save项。

  (2)使用Set Accelerator方法可以将加速器关联到一个菜单项。该方法使用KeyStroke类型的对象作为参数;

  (3)当用户按下加速器组合键时,就会自动选择了相应的菜单项,同时集火一个动作事件;

  (4)加速器只能关联在菜单项,而不能关联菜单;

  (5)加速器实际上并不打开菜单,而是直接激活菜单关联的动作事件。

8、启用和禁用菜单项:

  (1)在程序运行过程中,经常需要屏蔽某些暂时不适用的命令,待到条件允许时再使之重新利用。

  (2)屏蔽/启用菜单项的方法:

  aMenuItem.setEnable(boolean);

  当参数值为false时,屏蔽该菜单项;

  当参数值为true时,启用该菜单项。

  (3)如果需要动态启用/屏蔽某菜单项,则需要为菜单项注册“menuSelected”事件监听器;

  Javax.swing.event 包定义了MenuListener接口,它有三个方法:

  ——void   menuSelected(Menu Event   event)

  ——void  menuDeselected(MenuEvent  event)

  ——void  menuCanceled(MenuEvent  event)

9、工具栏:

  (1)工具栏在程序中提供快速访问常用命令的按钮栏;

  (2)工具栏的优点在于可以移动,脱离菜单栏或拖拽到框架其他地方;

  (3)关闭包含工具栏的框架后,工具栏回到原始的框架中。

  (4)工具提示:

  提示工具栏中某个按钮的含义。当光标停留在某个按钮上时,工具提示就会激活,工具提示文本显示在一个矩形里。当用户移开鼠标时,工具提示就会自动消失;

  调用setToolTest方法添加工具提示到JComponent;

  另一种方法就是,如果使用Action对象,就可以用SHORT-DESCRIPTION关联工具提示:

10、对话框:

  (1)对话框是一种大小不能变化、不能有菜单的容器窗口;

  (2)对话框不能作为一种应用程序的主框架,而必须包含在其他的容器当中;

  (3)Java提供多种形式的对话框;

  ——JOptionPane类:支持简单、标准的对话框;

  ——JFileChooser类:支持文件打开、保存对话框;

  ——ProgressMonitor类:支持操作进度条控制对话框等。

  (4)对话框依赖于框架,当框架撤销时,依赖该框架的对话框也会撤销,当框架窗口恢复时,依赖框架的对话框也会返回到屏幕;

  (5)对话框分为有模式和无模式两种:

    1)有模式的对话框处于激活状态时,程序只能响应对话框内部的事件,不能再激活它所依赖的窗口或组件,而且它将堵塞当前线程的执行,即堵塞使得对话框处于激活状态的线程,直到该对话框消失不可见;

    2)无模式对话框处于激活状态时,程序仍能激活它所依赖的窗口或者组件,它不能堵塞线程的执行。

11、选项对话框:

  (1)JOptionPane提供的对话框是模式对话框,当模式对话框显示时,它不允许用户输入到程序的其他的窗口,使用JOptionPane,可以创建和对定义问题、信息、警告、和错误等几种类型的对话框。

  (2)创建对话框:

  对话框的构造方法:

  ——JDialog  (Frame  owner)   ——构造一个没有标题的非模式对话框

  ——JDialog(Frame  owner ,  boolean  modal)  ——构造一个没有标题的对话框,boolean 型参数modal指定对话框是否为模式窗口

  ——JDialog(Frame owner ,String  title)  ——构造一个有标题的非模式对话框

  ——JDialog(Frame  owner , String  title,  boolean  modal)  ——构造一个有标题的对话框。

JFrameChooser 为用户选择文件提供了一种简单的机制,其方法有: 
boolean accept(File f) 
 如果应该显示该文件,则返回 true。 
 void addActionListener(ActionListener l) 
 向文件选择器添加一个 ActionListener。 
 void addChoosableFileFilter(FileFilter filter) 
 向用户可选择的文件过滤器列表添加一个过滤器。 
 void approveSelection() 
 用户单击 Approve 按钮(默认情况下标有 "Open" 或 "Save")时由 UI 调用此方法。 
 void cancelSelection() 
 用户选择 Cancel 按钮时由 UI 调用此方法。 
 void changeToParentDirectory() 
 将要设置的目录更改为当前目录的父级。 
protected JDialog creatDialog(Component parent) 
 创建并返回包含 this 的新 JDialog,在 parent 窗体中的 parent 上居中。 
 void ensureFileIsVisible(File f) 
 确保指定的文件是可见的,不是隐藏的。 
protected void fireActionPerformed(String command) 
 通知对此事件类型感兴趣的所有侦听器。 
 FileFilter getAcceptAllFileFilter() 
 返回 AcceptAll 文件过滤器。 
 AccessibleContext getAccessibleContext() 
 获取与此 JFileChooser 关联的 AccessibleContext。 
 JComponent getAccessory() 
 返回 accessory 组件。 
 ActionListener[] getActionListeners() 
 返回在此文件选择器上注册的所有操作侦听器的数组。 
 int getApproveButtonMnemonic() 
 返回确认按钮的助记符。 
 String getApproveButtonText() 
 返回 ApproveButton 中的 FileChooserUI 内使用的文本。 
 String getApproveButtonToolTipText() 
 返回 ApproveButton 中使用的工具提示文本。 
 FileFilter[] getChoosableFileFilters() 
 获得用户可选择的文件过滤器列表。 
 boolean getControlButtonsAreShown() 
 返回 controlButtonsAreShown 属性的值。 
 File getCurrentDirectory() 
 返回当前目录。 
 String getDescription(File f) 
 返回文件描述。 
 String getDialogTitle() 
 获得 JFileChooser 的标题栏中所显示的字符串。 
 int getDialogType() 
 返回此对话框的类型。 
 boolean getDragEnabled() 
 获得 dragEnabled 属性的值。 
 FileFilter getFileFilter() 
 返回当前选择的文件过滤器。 
 int getFileSelectionMode() 
 返回当前的文件选择模式。 
 FileSystemView getFileSystemView() 
 返回文件系统视图。 
 FileView getFileView() 
 返回当前的文件视图。 
 Icon getIcon(File f) 
 返回此文件或文件类型的图标,这取决于系统。 
 String getName(File f) 
 返回文件名。 
 File getSelectedFile() 
 返回选中的文件。 
 File[] getSelectedFiles() 
 如果将文件选择器设置为允许选择多个文件,则返回选中文件的列表。 
 String getTypeDescription(File f) 
 返回文件类型。 
 FileChooserUI getUI() 
 获得实现此组件 L&F 的 UI 对象。 
 String getUIClassID() 
 返回一个指示 L&F 类名的字符串,该类负责呈现此组件。 
 boolean isAcceptAllFileFilterUsed() 
 返回是否使用 AcceptAll FileFilter。 
 boolean isDirectorySelectionEnabled() 
 方便的调用,可根据当前的文件选择模式确定目录是否为可选择的。 
 boolean isFileHidingEnabled() 
 如果在文件选择器中不显示隐藏文件,则返回 true;否则返回 false。 
 boolean isFileSelectionEnabled() 
 方便的调用,可根据当前的文件选择模式确定文件是否为可选择的。 
 boolean isMultiSelectionEnabled() 
 如果可以选择多个文件,则返回 true。 
 boolean isTraversable(File f) 
 如果可以返回该文件(目录),则返回 true。 
protected String paramString() 
 返回此 JFileChooser 的字符串表示形式。 
 void removeActionListener(ActionListener l) 
 从文件选择器中移除一个 ActionListener。 
 boolean removeChoosableFileFilter(FileFilter f) 
 从用户可选择的文件过滤器列表中移除一个过滤器。 
 void rescanCurrentDirectory() 
 通知 UI 重新扫描当前目录的文件列表。 
 void resetChoosableFileFilters() 
 将可选择文件过滤器列表重置为其开始状态。 
 void setAcceptAllFileFilterUsed(boolean b) 
 确定是否将 AcceptAll FileFilter 用作可选择过滤器列表中一个可用选项。 
 void setAccessory(JComponent newAccessory) 
 设置 accessory 组件。 
 void setApproveButtonMnemonic(char mnemonic) 
 使用字符设置确认按钮的助记符。 
 void setApproveButtonMnemonic(int mnemonic) 
 使用数值键代码设置确认按钮的助记符。 
 void setApproveButtonText(String approveButtonText) 
 设置 FileChooserUI 中的 ApproveButton 内使用的文本。 
 void setApproveButtonToolTipText(String toolTipText) 
 设置 ApproveButton 中使用的工具提示文本。 
 void setControlButtonsAreShown(boolean b) 
 设置属性,指示在文件选择器中是否显示 approve 和 cancel 按钮。 
 void setCurrentDirectory(File dir) 
 设置当前目录。 
 void setDialogTitle(String dialogTitle) 
 设置显示在 JFileChooser 窗口标题栏的字符串。 
 void setDialogType(int dialogType) 
 设置此对话框的类型。 
 void setDragEnabled(boolean b) 
 设置 dragEnabled 属性,要在此组件上启用自动拖动处理(drag 和 drop 的第一部分),此属性必须为 true。 
 void setFileFilter(FileFilter filter) 
 设置当前文件过滤器。 
 void setFileHidingEnabled(boolean b) 
 设置是否实现文件隐藏。 
 void setFileSelectionMode(int mode) 
 设置 JFileChooser,以允许用户只选择文件、只选择目录,或者可选择文件和目录。 
 void setFileSystemView(FileSystemView fsv) 
 设置为访问和创建文件系统资源(如查找软驱和获得根驱动器列表),JFileChooser 所使用的文件系统视图。 
 void setFileView(FileView fileView) 
 设置用于检索 UI 信息的文件视图,如表示文件的图标或文件的类型描述。 
 void setMultiSelectionEnabled(boolean b) 
 设置文件选择器,以允许选择多个文件。 
 void setSelectedFile(File file) 
 设置选中的文件。 
 void setSelectedFiles(File[] selectedFiles) 
 如果将文件选择器设置为允许选择多个文件,则设置选中文件的列表。 
protected void setup(FileSystemView view) 
 执行公共的构造方法初始化和设置。 
 int showDialog(Component parent, String approveButtonText) 
 弹出具有自定义 approve 按钮的自定义文件选择器对话框。 
 int showOpenDialog(Component parent) 
 弹出一个 "Open File" 文件选择器对话框。 
 int showSaveDialog(Component parent) 
 弹出一个 "Save File" 文件选择器对话框。 
 void updateUI() 
 将 UI 属性重置为当前的外观值。
文本对话框:

1,Swing提供了JFileChoose类,特可以显示一个文件对话框。

2,JFileChoose类并不是JDialog类的子类。需要调用showOpenDialog,而不是调用setVisibel(true)来显示打开文件的对话框,或者调用showSaveDialog显示保存文件的对话框。接收文件的按钮被标签为Open或者Save,也可以调用showDialog方法制定自己的标签。

3,调用showOpenDialog或者showSaveDialog方法显示对话框。必须为这些调用提供父组件:

Int result = chooser.showOepnDialog(parent);

或者

Int result = chooser.showSaveDialog(parent);

这些调用的区别就是“确认按钮”的标签不同,点击“确认按钮”完成文件选择。也可以调用showDialog方法并将一个显示的文本传递个确认按钮。

Int result = chooser.showDialog(parent,”select”);

仅当用户确认、取消或者离开文件对话框时才返回调用。返回值可以是JFileChoose.APPROVE_OPEION,JFileChooser.CANCLE_OPTION或者JFileChooser.ERROR_OPTION。

4,若想限制显示的文件,需要创建扩展了抽象类javax.swing.filechooser.FileFilter的对象。文件选择器把每个文件传递个过滤器,只有文件过滤器接受的文件才被最终显示出来。编写专用文件过滤器非常简单,只要事先FileFilter子类中的两个抽象方法即可:

Public boolean accept(File f);

Public String getDescription();

第一个方法测试是否应该接受一个文件。第二个方法返回显示在文件选择器对话框中的文件类型的说明信息。例如,如果值选择GIF文件,可以使用下面的代码:

Public clas GifFilter extends FileFilter

{

Public boolean accept(File f)

{

Return f.getName().toLowerCase().endsWith(“.gif”)||f.isDirectory();

}

Public String getDescription()

{

Return “GIF Image”;

}

}

一旦有个文件过滤对象,就可以使用JFileChoose类的setFileFilter方法,将这个对象安装到文件选择器对象中:

chooser.setFileFilter(new GifFilter());

在市里程序中,提供了一个ExtensionFileFilter类,其用法如下:

ExtensionFileFilter filter = new ExtensionFileFilter();

filter.addExtension(“jpg”);

filter.addExtension(“gif”);

filter.setDescription(“image files”);

ExrensionFileFilter类的事先不过是对GifFilter类的一个简要总结。可以在自己的程序中使用这个类。

5,通过添加对文件选择器显示的每个文件的特殊图标和文件说明来定制自己的文件选择器。这需要扩展javax.swing.filechooser包中的FileView类。这是一项高级的技巧。在通常情况下,不需要提供文件视图——可插观感会提供。但是如果想为特殊的文件类型显示不同的图标,就需要安装自己的文件视图。这要扩展FileView并实现下面5个方法:

Icon getIcon(File f);

String getName(File f);

String getDescription(File f);

String getTypeDescription(File f);

Boolean isTraversable(File f);

然后,使用setFileView方法将文件视图安装到文件选择器中。

使用setFileView方法可以将文件视图安装到文件选择器中:

chooser.setFileView(new FileIconView(filter,new ImageIcon(“palette.gif”)));

第二部分:实验部分

实验1:测试程序1(7分)

实验代码如下:

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;   //Action类对象
   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)   //TestAction构造器,String name为如口参数
      {
         super(name);   //完成父类的构造
      }

      public void actionPerformed(ActionEvent event)    //actionPerformed方法
      {
         System.out.println(getValue(Action.NAME) + " selected.");
         //将选择的菜单按钮信息输出在控制台上。
      }
   }

   public MenuFrame()   //MenuFrame构造器
   {
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      //设置大小为两个常量值
      JMenu fileMenu = new JMenu("File");    //新建一个File菜单
      fileMenu.add(new TestAction("New"));   //调用fileMenu类对象的add方法将新建的TestAction类对象New添加到File菜单当中

      // demonstrate accelerators

      JMenuItem openItem = fileMenu.add(new TestAction("Open")); 
      //添加子菜单
      openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
      //调用setAccelerator方法将键盘中的ctrl O和open子菜单想关联
      fileMenu.addSeparator();
      //将一个分隔符添加到菜单中
      saveAction = new TestAction("Save");    //新建一个Action类对象
      JMenuItem saveItem = fileMenu.add(saveAction);    //新建一个子菜单,将其添加到file菜单当中
      saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
      //调用setAccelerator方法将键盘中的ctrl S和save子菜单想关联
      saveAsAction = new TestAction("Save As");    //新建一个
      fileMenu.add(saveAsAction);     //将Save As添加到file菜单当中
      fileMenu.addSeparator();     //将一个分隔符添加到菜单中

      fileMenu.add(new AbstractAction("Exit")       //将Exit子菜单添加到file菜单当中
         {
            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);   
               //设置 Action 的启用状态。在启用时,任何与此对象相关联的组件都被激活,并且都能触发此对象的 actionPerformed 方法。
               saveAsAction.setEnabled(saveOk);  
            }
         });

      ButtonGroup group = new ButtonGroup();
      //新建一个按钮组对象
      JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert");
      //新建一个JRadioButtonMenuItem类对象,单选按钮的子菜单
      insertItem.setSelected(true);     //设置单选按钮Insert是选中的
      JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype");
      //新建一个单选按钮Overtype
      group.add(insertItem);   //将新建的JRadioButtonMenuItem类对象insertItem和overtypeItem加入到按钮组当中
      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");  //新建一个Edit菜单
      editMenu.add(cutAction);   //将cutAction,copyAction,pasteAction动作添加到Edit菜单
      editMenu.add(copyAction);
      editMenu.add(pasteAction);

      // demonstrate nested menus

      JMenu optionMenu = new JMenu("Options");
      //新建一个Options菜单
      optionMenu.add(readonlyItem);  //将readonlyItem、insertItem、overtypeItem添加到选择菜单当中
      optionMenu.addSeparator();     //将一个分隔符添加到菜单中
      optionMenu.add(insertItem);
      optionMenu.add(overtypeItem);

      editMenu.addSeparator();   
      editMenu.add(optionMenu); //将optionMenu子菜单添加到editMenu菜单当中

      // demonstrate mnemonics

      JMenu helpMenu = new JMenu("Help");
      helpMenu.setMnemonic('H');  

      JMenuItem indexItem = new JMenuItem("Index");
      indexItem.setMnemonic('I');
      helpMenu.add(indexItem);   //将Index菜单添加到help菜单当中

      // 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);  //将aboutAction添加到helpMenu菜单当中
      
      // add all top-level menus to menu bar

      JMenuBar menuBar = new JMenuBar();   //新建一个JMenuBar( 菜单栏) :用来放置JMenu组件的菜单容器, 可添加到 JFrame组件上。
      setJMenuBar(menuBar);   //窗口添加 子菜单

      menuBar.add(fileMenu);   //将fileMenu、editMenu、helpMenu子菜单添加到menuBar主菜单当中
      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类对象
      panel.setComponentPopupMenu(popup);   //调用组件弹出菜单setComponentPopupMenu方法将弹出菜单添加到面板上
      add(panel);  //将面板添加到JFrame当中
   }
}

  运行结果如下:

  

实验1:测试程序2(7分)

 实验代码如下:

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()    //ToolBarFrame构造器
   { 
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      //设置框架的大小为宽为DEFAULT_WIDTH,高DEFAULT_HEIGHT
      // add a panel for color change

      panel = new JPanel();   //创建一个面板类对象
      add(panel, BorderLayout.CENTER);    //添加到panel,采用边框布局管理方式的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);   //将blueAction、yellowAction、redAction、exitAction动作添加到工具栏当中
      bar.add(yellowAction);
      bar.add(redAction);
      bar.addSeparator();   //将一个分隔符一俺家到工具栏当中
      bar.add(exitAction);
      add(bar, BorderLayout.NORTH);     //采用边框布局管理器,放在NORTH的位置

      // populate menu

      JMenu menu = new JMenu("Color");   //新建一个菜单类对现象
      menu.add(yellowAction);    //将yellowAction、blueAction、redAction、exitAction动作添加到菜单当中
      menu.add(blueAction);
      menu.add(redAction);
      menu.add(exitAction);
      JMenuBar menuBar = new JMenuBar();    //新建一个JMenuBar菜单栏
      menuBar.add(menu);   //将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)   //ColorAction构造器
      {
         putValue(Action.NAME, name);    //调用putValue方法来存值
         putValue(Action.SMALL_ICON, icon);
         putValue(Action.SHORT_DESCRIPTION, name + " background");
         putValue("Color", c);  
      }

      public void actionPerformed(ActionEvent event)
      {
         Color c = (Color) getValue("Color");     //将得到的值强转为Color类,
         panel.setBackground(c);    //设置为面板的背景颜色
      }
   }
}

  运行结果如下:

  

实验1:测试程序3(7分)

 实验代码如下:

 

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 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";    //字符串Message
   private Icon messageIcon = new ImageIcon("blue-ball.gif");   //标签
   private Object messageObject = new Date();   
   private Component messageComponent = new SampleComponent();   //组件  

   public OptionDialogFrame()     //OptionDialogFrame构造器
   { 
      JPanel gridPanel = new JPanel();   //新建一个JPanel类对象
      gridPanel.setLayout(new GridLayout(2, 3));   //设置网格布局管理方式,两行三列

      typePanel = new ButtonPanel("Type", "Message", "Confirm", "Option", "Input");
      //Type中M有Message、Confirm、Option、Input五种选择按钮
      messageTypePanel = new ButtonPanel("Message Type", "ERROR_MESSAGE", "INFORMATION_MESSAGE",
            "WARNING_MESSAGE", "QUESTION_MESSAGE", "PLAIN_MESSAGE");
      //Message Type中有ERROR_MESSAGE、INFORMATION_MESSAGE、WARNING_MESSAGE、QUESTION_MESSAGE、PLAIN_MESSAGE六种选择按钮
      messagePanel = new ButtonPanel("Message", "String", "Icon", "Component", "Other", 
            "Object[]"); 
      //Message中有String、Icon、Component、Other、Object[]五种选择按钮
      optionTypePanel = new ButtonPanel("Confirm", "DEFAULT_OPTION", "YES_NO_OPTION",
            "YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION");
      //Confirm中有DEFAULT_OPTION、YES_NO_OPTION、YE、S_NO_CANCEL_OPTION、OK_CANCEL_OPTION四种选择按钮
      optionsPanel = new ButtonPanel("Option", "String[]", "Icon[]", "Object[]"); 
      //Option面板当中有String[]、Icon[]、Object[]三种选择按钮
      inputPanel = new ButtonPanel("Input", "Text field", "Combo box");
      //Input当中有Text field、Combo 两种选择按钮
      gridPanel.add(typePanel);   
      //将typePanel、messageTypePanel、optionTypePanel、optionsPanel、inputPanel添加到两行三列的网格布局管理的面板当中
      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();   //新建一个JPanel类对象,
      JButton showButton = new JButton("Show");   //新建一个Show按钮  ,
      showButton.addActionListener(new ShowAction());//添加动作监听器
      showPanel.add(showButton);    //将Show按钮添加到showPanel面板上
 
      add(gridPanel, BorderLayout.CENTER);   //将网格面板添加到边框布局管理的CENTER位置
      add(showPanel, BorderLayout.SOUTH);    //将网格面板添加到边框布局管理的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));
         //如果typePanel中选择Confirm按钮,得到messageTypePanel内容
         else if (typePanel.getSelection().equals("Input"))  //如果选择Input按钮
         {
            if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog(
                  OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
            //如果Input面板当中选择的是Text field,得到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));
         //选择的是Message
         else if (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog(
               OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
               getType(messageTypePanel), null, getOptions(), getOptions()[0]);
         //选择的是Option
      }
   }
}

/**
 * A component with a painted surface
 */

class SampleComponent extends JComponent   
{
   public void paintComponent(Graphics g)     //paintComponent方法
   {
      Graphics2D g2 = (Graphics2D) g;
      Double rect = new Rectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1);
      //
      g2.setPaint(Color.YELLOW);    //调用setPaint方法来设置颜色为YELLOW
      g2.fill(rect);   //填充
      g2.setPaint(Color.BLUE);
      g2.draw(rect);
   }

   public Dimension getPreferredSize()
   {
      return new Dimension(10, 10);
   }
}

  

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)   //ButtonPanel构造器
   {
      setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
      //设置边框的凹下去的效果,BorderFactory这个类里还有凸出来的效果
      setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));    
      //this 表示的是这个当前对象
      group = new ButtonGroup();   //新建一个按钮组对象

      // make one radio button for each option
      for (String option : options)
      { 
         JRadioButton button = new JRadioButton(option);   //新建一个JRadioButton类对象
         button.setActionCommand(option);   //调用setActionCommand方法
         add(button);   //添加button按钮
         group.add(button);   //将button按钮添加到按钮组当中
         button.setSelected(option == options[0]);    //设置为可选择的
      }
   }

   /**
    * Gets the currently selected option.
    * @return the label of the currently selected radio button.
    */
   public String getSelection()    //getSelection方法,String类型
   {
      return group.getSelection().getActionCommand();
   }
}

运行结果如下:

实验1:测试程序4(7分)

 实验代码如下:

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;   //定义一个私有类AboutDialog

   public DialogFrame()    //DialogFrame构造器
   {
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);   //设置框架的大小为宽为DEFAULT_WIDTH、高为DEFAULT_HEIGHT的框架

      // construct a File menu

      JMenuBar menuBar = new JMenuBar();  //新建一个菜单栏类对象
      setJMenuBar(menuBar);   
      JMenu fileMenu = new JMenu("File");  //新建一个菜单类对象fileMenu,File菜单
      menuBar.add(fileMenu);   //将菜单添加到菜单栏当中

      // add About and Exit menu items

      // the About item shows the About dialog

      JMenuItem aboutItem = new JMenuItem("About");   //新建一个About子菜单
      aboutItem.addActionListener(event -> {
         if (dialog == null) // first time
            dialog = new AboutDialog(DialogFrame.this);
         dialog.setVisible(true); // pop up dialog 
      });
      fileMenu.add(aboutItem);   //将子菜单添加到fileMenu菜单当中

      // the Exit item exits the program

      JMenuItem exitItem = new JMenuItem("Exit");   //新建一个子菜单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)  //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);
     //设置为边框布局管理方式,放置CENTER位置
      // OK button closes the dialog

      JButton ok = new JButton("OK");   //新建一个JButton类对象,OK按钮
      ok.addActionListener(event -> setVisible(false));   
      //设置组件可见
      // add OK button to southern border

      JPanel panel = new JPanel();
      panel.add(ok);   //将ok按钮添加到面板上
      add(panel, BorderLayout.SOUTH);   //将面板添加到边框布局管理方式中的SOUTH位置

      pack();   //考虑首选组件的大小
   }
}

  运行结果如下:

实验1:测试程序5(7分)

 实验代码如下:

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.*;
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;   //私有类PasswordChooser的定义
   private JTextArea textArea;  //私有类文本域JTextArea的定义

   public DataExchangeFrame()   //DataExchangeFrame构造器
   {
      // construct a File menu

      JMenuBar mbar = new JMenuBar();  
      setJMenuBar(mbar);  
      JMenu fileMenu = new JMenu("File");   //新建一个菜单,File菜单
      mbar.add(fileMenu);   //将File菜单添加到菜单栏当中

      // add Connect and Exit menu items
 
      JMenuItem connectItem = new JMenuItem("Connect");  //新建一个Connect子菜单
      connectItem.addActionListener(new ConnectAction());  //添加其动作监听器
      fileMenu.add(connectItem);  //将子菜单添加到file菜单当中

      // the Exit item exits the program

      JMenuItem exitItem = new JMenuItem("Exit"); //新建一个Exit子菜单
      exitItem.addActionListener(event -> System.exit(0));   //添加其监听器
      fileMenu.add(exitItem);   //将编辑exitItem子菜单添加到file菜单当中

      textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);   //新建一个文本域类对象,TEXT_ROWS行、TEXT_COLUMNS列
      add(new JScrollPane(textArea), BorderLayout.CENTER);  //将新建的JScrollPane滑动条,放置在边框布局管理方式的CENTER位置
      pack();
   }

   /**
    * The Connect action pops up the password dialog.
    */
   private class ConnectAction implements ActionListener   //定义一个实现ActionListener接口的类ConnectAction
   {
      public void actionPerformed(ActionEvent event)
      {
         // if first time, construct dialog

         if (dialog == null) dialog = new PasswordChooser();
         //对话框是空的,新建一个PasswordChooser类对象赋给dialog
         // set default values
         dialog.setUser(new User("yourname", null));
         //提示语,yourname
         // pop up dialog
         if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
         {
            // if accepted, retrieve user input
            User u = dialog.getUser();  //调用对话框的getUser方法得到的名字赋给u
            textArea.append("user name = " + u.getName() + ", password = "
               + (new String(u.getPassword())) + "\n");
            //在文本域中输出用户输入的名字以及密码
         }
      }
   }
}

  

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()   //PasswordChooser构造器
   {
      setLayout(new BorderLayout());  
      //创建一个边框布局管理类
      // construct a panel with user name and password fields

      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(2, 2));    //面板的网格布局管理,2行2列
      panel.add(new JLabel("User name:"));   //将User name:标签添加到面板上
      panel.add(username = new JTextField(""));    //输入文本框
      panel.add(new JLabel("Password:"));   //将Password:标签添加到面板上
      panel.add(password = new JPasswordField(""));  //输入文本框
      add(panel, BorderLayout.CENTER);  //将面板添加到边框布局管理器的CENTER位置

      // create Ok and Cancel buttons that terminate the dialog

      okButton = new JButton("Ok");   //新建一个ok按钮
      okButton.addActionListener(event -> {
         ok = true;  
         dialog.setVisible(false);  //设置对话框的组件可见
      });

      JButton cancelButton = new JButton("Cancel");  //新建一个Cancel取消按钮
      cancelButton.addActionListener(event -> dialog.setVisible(false));
      //调用取消按钮的添加监听器方法,设置组件不可见
      // add buttons to southern border

      JPanel buttonPanel = new JPanel();  //新建一个面板对象
      buttonPanel.add(okButton);   //将ok按钮添加到面板当中
      buttonPanel.add(cancelButton);   //将取消按钮添加到面板当中
      add(buttonPanel, BorderLayout.SOUTH);   //将按钮面板添加到边框布局管理器的SOUTH位置
   }

   /**
    * Sets the dialog defaults.
    * @param u the default user information
    */
   public void setUser(User u)  //setUser方法
   {
      username.setText(u.getName());   //调用getName方法得到名字,再调用setText方法将用户名称放在文本当中,
   }

   /**
    * 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)   //User构造器
   {
      name = aName;
      password = aPassword;
   }

   public String getName()   //getName方法
   {
      return name;  //返回名字
   }

   public char[] getPassword()  //getPassword方法
   { 
      return password;  //返回密码
   }

   public void setName(String aName)  //setName方法
   {
      name = aName;
   }
 
   public void setPassword(char[] aPassword)  //setPassword方法
   {
      password = aPassword;
   }
}

  运行结果如下:

      

实验1:测试程序6(7分)

 实验代码如下:

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);
      });
   }
}

 

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)  //FileIconView构造器,两个入口参数
   {
      filter = aFilter;
      icon = anIcon;
   }

   public Icon getIcon(File f)   //getIcon方法获得此文件或文件类型的图标,这取决于系统。
   {
      if (!f.isDirectory() && filter.accept(f)) return icon;
      //可根据当前的文件选择模式确定目录是否为可选择的。
      else return null;
   }
}

 

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)   //ImagePreviewer构造器,JFileChooser chooser是入口参数
   {
      setPreferredSize(new Dimension(100, 100)); 
      //setPreferredSize需要在使用布局管理器的时候使用,布局管理器会获取空间的PreferredSize,因而可以生效。
      setBorder(BorderFactory.createEtchedBorder());
      //设置边框的凹下去的效果,BorderFactory这个类里还有凸出来的效果
      chooser.addPropertyChangeListener(event -> {
         if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
         {
            // the user has selected a new file
            File f = (File) event.getNewValue();   //获得新的值,强转为File类型
            if (f == null)
            {
               setIcon(null); //此文件或文件类型的图标,这取决于系统。 
               return;
            }

            // read the image into an icon
            ImageIcon icon = new ImageIcon(f.getPath());
            //新建一个图标,指定图像
            // if the icon is too large to fit, scale it
            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;   //JFileChooser 用来提供一个文件对话框 

   public ImageViewerFrame()        //ImageViewerFrame构造器
   {
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);  //框架的整体大小,宽DEFAULT_WIDTH,高DEFAULT_HEIGHT

      // set up menu bar
      JMenuBar menuBar = new JMenuBar();   //新建一个菜单栏
      setJMenuBar(menuBar);    //设置到框架当中

      JMenu menu = new JMenu("File");   //新建一个File菜单
      menuBar.add(menu);  //将File菜单添加到菜单栏当中

      JMenuItem openItem = new JMenuItem("Open");   //新建一个子菜单Open
      menu.add(openItem);   //将子菜单添加到菜单当中
      openItem.addActionListener(event -> {    //添加动作监听器
         chooser.setCurrentDirectory(new File("."));
         //使用setCurrentDirectory函数来改变进程的当前目录。
         // show file chooser dialog
            int result = chooser.showOpenDialog(ImageViewerFrame.this);
            //调用showOpenDialog方法,显示打开文件的对话框。等同于 ImageViewer view = new ImageViewer();
            //但是必须在 当前类中 也就是ImageViewerFrame中才能这么写;this 表示本类;提供组件
            // if image file accepted, set it as icon of the label
            if (result == JFileChooser.APPROVE_OPTION)    //如果用户选择了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));
      //添加动作监听器
      // use a label to display the images
      label = new JLabel();  //新建一个标签
      add(label);    //添加该标签

      // set up file chooser
      chooser = new JFileChooser();   //新建一个JFileChooser类对象

      // accept all image files ending with .jpg, .jpeg, .gif
      //创建FileFilter的子类,用以实现文件过滤功能 
      FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "Image files", "jpg", "jpeg", "gif");   //接受所有以jpg, .jpeg, .gif为扩展名的图像文件
      chooser.setFileFilter(filter);   //setFIlefilter 是设置它的文件过滤器  filter是具体的过滤器规则
      //一旦有个文件过滤对象,就可以使用JFileChoose类的setFileFilter方法,将这个对象安装到文件选择器对象中
      chooser.setAccessory(new ImagePreviewer(chooser));
      
      chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif")));
   }//使用setFileView方法可以将文件视图安装到文件选择器中
}

  运行结果如下:

                              

 

实验1:测试程序7(7分)

 实验代码如下:

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()    //ColorChooserFrame构造器
   {      
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); //设置为两个常量大小的框架

      // add color chooser panel to frame

      ColorChooserPanel panel = new ColorChooserPanel();  //创建一个ColorChooserPanel类对象panel
      add(panel); //将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()      //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);   //设置组件可见
      }
   }
}

  运行结果如下:

       

实验总结:(16分)

   这一周,学习了菜单和对话框的相关知识,理论知识老师讲的挺详细的,大概都能听得懂。实验都是验证性的实验,就是给新学习的知识添加注释,在添加注释的时候,有些地方还是掌握的不太好,有些还是不知道其具体作用,然后就提通过网络或者查书来解决。最后理解了代码。这周的结对编程,老师没有要求写在博客园上,我大概看了一下,和实验的第一个程序比较像,但是在此基础上还得添加。

posted on 2019-12-09 12:45  黎沫  阅读(331)  评论(1编辑  收藏  举报