夏热握火

导航

201871010125-王玉江《面向对象程序设计(java)》第十五周学习总结

项目

内容

这个作业属于哪个课程

<任课教师博客主页链接>

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

这个作业的要求在哪里

<作业链接地址>

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

作业学习目标

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

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

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

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

 

菜单是图形用户界面的重要组成部分,它通常有两种使用方式:窗口菜单和快捷菜单。下面介绍窗口菜单的创建。
窗口菜单是由菜单条(MenmBar)、 菜单(Memu)、菜单项(Menltem)和复选菜单项CeckoMonultem等组成的。菜单放在菜单条里,菜单项放在菜单里。

(1)菜单条(MenBar)。

Java.awt包中的MenuBar类是负责创建菜单条的,即MenuBar类的一个实例就是一个菜单条。菜单条只能被添加到作为Frame对象中,整个菜单树的根基。
Frame类有一个将菜单条放置到窗口中的方法:
setMenuBar (MenuBar bar)
该方法将菜单条添加到窗口的顶端,需要注意的是,只能向窗口添加一个菜单条。

例如:
MenuBar MenuBar1 = new MenuBar()                   //创建菜单条
setMenuBar (MenuBar1)                                              //添加创建菜单条到Frame中
(2)菜单(Menu)。

Menu类负责创建菜单,即Menu类的一个实例就是一个菜单。 无法直接将菜单添加到容器的某位置,也无法使用布局管理器对其加以控制。菜单只能被添加到“菜单容器”菜单条(MenuBar) 中。
例如:
Menu Menu1=new Menu("文件")                                  //创建菜单
menubar . add (Menu1)                                                //添加到菜单条中
(3)菜单项(Menultem)。

MenuItem类是负责创建菜单项的,即MenuItem类的一个实例就是一个菜单项。菜单项必须添加到菜单中。MenuItem是整个“菜单树”中的“叶子节点”。Menultem对象可以添加ActionListener,使其能完成相应的操作,在后面的章节中会学习相关知识。
例如:
MenuItem item1=new MenuItem ("新建")                     //创建菜单项
menul . add (item1)                                                      //添加到菜单中


工具栏:

工具栏中提供了快速执行常用命令的按钮,可以将它随意拖拽到窗体的四周,JToolBar 工具栏相当于一个组件的容器,可以添加按钮,微调控制器等组件到工具栏中。每个添加的组件会被分配一个整数的索引,来确定这个组件的显示顺序。另外,组件可以位于窗体的任何一个边框,也可以成为一个单独的窗体。

注意:如果希望工具栏可以随意拖动,窗体一定要采用默认的边界布局方式,并且不能在边界布局的四周添加任何组件。

工具栏默认是可以随意拖动的。

常用构造方法
JToolBar():建立一个新的JToolBar,位置为默认的水平方向.

JToolBar(int orientation):建立一个指定的JToolBar.

JToolBar(String name):建立一个指定名称的JToolBar.

JToolBar(String name,int orientation):建立一个指定名称和位置的JToolBar.

入口参数代表的意思:

name:工具栏名称,悬浮显示时为悬浮窗口的标题。

orientation:工具栏的方向,值为HORIZONTAL (水平方向,默认值)或 VERTICAL(垂直方向)

注意:在使用JToolBar时一般都采用水平方向的位置,因此我们在构造时多是采用上表中的第一种构造方式来建立JToolBar,如果需要改变方向时再用JToolBar内的setOrientation()方法来改变设置,或是以鼠标拉动的方式来改变JToolBar的位置。

 

public JButton add(Action a) : 向工具栏中添加一个指派动作的新的Button

public void addSeparator() : 将默认大小的分隔符添加到工具栏的末尾

public Component getComponentAtIndex(int i) : 返回指定索引位置的组件

public int getComponentIndex(Component c) : 返回指定组件的索引

public int getOrientation() : 返回工具栏的当前方向

public boolean isFloatable() : 获取Floatable 属性,以确定工具栏是否能拖动,如果可以则返回true,否则返回false

public boolean isRollover () : 获取rollover 状态,以确定当鼠标经过工具栏按钮时,是否绘制按钮的边框,如果需要绘制则返回true,否则返回false

public void setFloatable(boolean b) : 设置Floatable 属性,如果要移动工具栏,此属性必须设置为true

.对话框
  对话框分为模式对话框和无模对话框,模式对话框就是未处理此对话框之前不允许与其他窗口交互。 
  JOptionPane 
    提供了四个用静态方法(showxxxx)显示的对话框: 
    构造对话框的步骤: 
      1)选择对话框类型(消息、确认、选择、输入) 
      2)选择消息类型(String/Icon/Component/Object[]/任何其他对象) 
      3)选择图标(ERROR_MESSAGE/INFORMATION_MESSAGE/WARNING_MESSAGE/QUESTION_MESSAGE/PLAIN_MESSAGE) 
      4)对于确认对话框,选择按钮类型(DEFAULT_OPTION/YES_NO_OPTION/YES_NO_CANCEL_OPTION/OK_CANCEL_OPTION) 
      5)对于选项对话框,选择选项(String/Icon/Component) 
      6)对于输入对话框,选择文本框或组合框 
      确认对话框和选择对话框调用后会返回按钮值或被选的选项的索引值 
   JDialog类 
      可以自己创建对话框,需调用超类JDialog类的构造器

      public aboutD extends JDialog
      {
        public aboutD(JFrame owner)
        {
          super(owner,"About Text",true);
           ....
        }
      }
    构造JDialog类后需要setVisible才能时窗口可见

    if(dialog == null)
    dialog = new JDialog();
    dialog.setVisible(true);
  文件对话框(JFileChooser类) 
  颜色对话框(JColorChooser类)

 

  对话框是一种大小不能变化、不能有菜单的容器窗口;对话框不能作为一个应用程序的主框架,而必须包含在其他的容器中。

  Java提供多种对话框类来支持多种形式的对话框。

  对话框依赖于框架。当框架撤销时,依赖该框架的对话框 也撤销。当框架图标化时,依赖它的对话框也从屏幕上消 失。当框架窗口恢复时,依赖框架的对话框又返回屏幕。 

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

数据交换:输入对话框含有供用户输入文本的文本框、一个确认和取 消按钮,是有模式对话框。当输入对话框可见时,要求用户 输入一个字符串。

文件对话框:专门用于对文件(或目录)进行浏览和选择的对 话框,常用的构造方法: – JFileChooser():根据用户的缺省目录创建文件对话框 – JFileChooser(File currentDirectory):根据File型参数 currentDirectory指定的目录创建文件对话框

颜色对话框: javax.swing包中的JColorChooser类的静态方 法: public static Color showDialog(Component component, String title, Color initialColor)创建一个颜色对话框

  参数component指定对话框所依赖的组件,title 指定对话框的标题;initialColor 指定对话框返回 的初始颜色,即对话框消失后,返回的默认值。 颜色对话框可根据用户在颜色对话框中选择的颜 色返回一个颜色对象.

  自己创建对话框,需调用超类JDialog类的构造器

  public aboutD extends JDialog
  {
  public aboutD(JFrame owner)
  {
    super(owner,"About Text",true);
    ....
  }
  }
  构造JDialog类后需要setVisible才能时窗口可见

  if(dialog == null)
  dialog = new JDialog();
  dialog.setVisible(true);

 

第二部分:实验部分

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

 elipse IDE中调试运行教材512页程序12-8,结合运行结果理解程序;

 掌握菜单的创建、菜单事件监听器、复选框和单选按钮菜单项、弹出菜单以及快捷键和加速器的用法。

 记录示例代码阅读理解中存在的问题与疑惑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
      });
   }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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;
 
   /**
    *在显示台上显示已选择动作名称
    */
   class TestAction extends AbstractAction
   {
      public TestAction(String name)
      {
         super(name);
      }
 
      public void actionPerformed(ActionEvent event)
      {
         System.out.println(getValue(Action.NAME) + " selected.");//getValue返回被存储的值
      }
   }
 
   public MenuFrame()
   {
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
 
      var fileMenu = new JMenu("File");//菜单定义
       
      fileMenu.add(new TestAction("New"));
 
      // 加速器
 
      var openItem = fileMenu.add(new TestAction("Open"));
      openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));//"ctrl O"设置为Open菜单项的加速器
 
      fileMenu.addSeparator();//添加分隔符行
 
      saveAction = new TestAction("Save");
      JMenuItem saveItem = fileMenu.add(saveAction);
      saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));//"ctrl S"设置为Save菜单项的加速器
 
      saveAsAction = new TestAction("Save As");
      fileMenu.add(saveAsAction);
       
      fileMenu.addSeparator();//添加分隔符行
 
      fileMenu.add(new AbstractAction("Exit")
         {
            public void actionPerformed(ActionEvent event)
            {
               System.exit(0);
            }
         });
 
      //复选框和单按钮菜单项
 
      readonlyItem = new JCheckBoxMenuItem("Read-only");
      readonlyItem.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               boolean saveOk = !readonlyItem.isSelected();
               saveAction.setEnabled(saveOk);//若"Read-only"复选框未被选择,Save、Save as菜单项均可执行点击操作
               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);
 
      // 展示图标
 
      var cutAction = new TestAction("Cut");
      cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));//putValue将值放置在动作对象内
      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);
 
      //展示子菜单
 
      var optionMenu = new JMenu("Options");
 
      optionMenu.add(readonlyItem);
      optionMenu.addSeparator();//分隔符
      optionMenu.add(insertItem);
      optionMenu.add(overtypeItem);
 
      editMenu.addSeparator();
       
      editMenu.add(optionMenu);
 
      //展示快捷键
 
      var helpMenu = new JMenu("Help");
      helpMenu.setMnemonic('H');//设置快捷字符,该字符在标签中以下划线的项式显示
 
      var indexItem = new JMenuItem("Index");
      indexItem.setMnemonic('I');
      helpMenu.add(indexItem);
 
      //在快捷键上添加动作
      var aboutAction = new TestAction("About");
      aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));
      helpMenu.add(aboutAction);
       
      // 将所有的顶部菜单添加到菜单栏上
 
      var 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);
 
      var panel = new JPanel();
      panel.setComponentPopupMenu(popup);//设置组件的弹出菜单
      add(panel);
   }
}

                                                             

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

 elipse IDE中调试运行教材517页程序12-9,结合运行结果理解程序;

掌握工具栏和工具提示的用法;

 记录示例代码阅读理解中存在的问题与疑惑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
      });
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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);
 
      // 设置动作
 
      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);//用action对象填充工具栏
      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);
      }
   }
}

  

 

 工具提示:

 

 拖拽工具栏:

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

 elipse IDE中调试运行教材544页程序12-1512-16,结合运行结果理解程序;

掌握选项对话框的用法。

 记录示例代码阅读理解中存在的问题与疑惑。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
      });
   }
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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();
 
      // 为每一个选项创建一个单选钮
      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
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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(23));
 
      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);
 
      // Show按钮的添加
 
      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();
   }
 
   /**
    *得到当前选择的信息
    * @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);//JOptionPane.xxx来获得这个静态字段的值
      }
      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), nullnew 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(00, getWidth() - 1, getHeight() - 1);
      g2.setPaint(Color.YELLOW);
      g2.fill(rect);
      g2.setPaint(Color.BLUE);
      g2.draw(rect);
   }
 
   public Dimension getPreferredSize()
   {
      return new Dimension(1010);
   }
}

  

 

 

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

elipse IDE中调试运行教材552页程序12-1712-18,结合运行结果理解程序;

 掌握对话框的创建方法;

记录示例代码阅读理解中存在的问题与疑惑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
      });
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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);
 
      //创建File菜单
 
      var menuBar = new JMenuBar();//菜单栏
      setJMenuBar(menuBar);
      var fileMenu = new JMenu("File");//菜单
      menuBar.add(fileMenu);
 
      //添加About、Exit菜单项
 
      //About项展示About对话框
 
      var aboutItem = new JMenuItem("About");//菜单项
      aboutItem.addActionListener(event -> {
         if (dialog == null// 只建立一次对话框,但可多次重复使用
            dialog = new AboutDialog(DialogFrame.this);
         dialog.setVisible(true);//显示对对话框
      });
      fileMenu.add(aboutItem);                                                                                                                                         
 
      // 关闭程序
 
      var exitItem = new JMenuItem("Exit");
      exitItem.addActionListener(event -> System.exit(0));
      fileMenu.add(exitItem);
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package dialog;
 
import java.awt.BorderLayout;
 
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
 
/**
 * A sample modal dialog that displays a message and waits for the user to click
 * the OK button.
 */
public class AboutDialog extends JDialog
{
   public AboutDialog(JFrame owner)
   {
      super(owner, "About DialogTest"true);
 
      //添加标签
 
      add(
         new JLabel(
            "<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"),
         BorderLayout.CENTER);
 
    //点击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();
   }
}

 

 

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

 elipse IDE中调试运行教材556页程序12-1912-20,结合运行结果理解程序;

 掌握对话框的数据交换用法;

 记录示例代码阅读理解中存在的问题与疑惑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
      });
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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()
   {
      // 创建File菜单
 
      var mbar = new JMenuBar();//菜单栏
      setJMenuBar(mbar);
      var fileMenu = new JMenu("File");//菜单
      mbar.add(fileMenu);
 
      //添加Connect、Exit菜单项
 
      var connectItem = new JMenuItem("Connect");//菜单项
      connectItem.addActionListener(new ConnectAction());
      fileMenu.add(connectItem);
 
      //关闭程序
 
      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 (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");
         }
      }
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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());
 
      //创建还有user name与password域的面板
 
      var panel = new JPanel();
      panel.setLayout(new GridLayout(22));
      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);//点击OK按钮后关闭对话框
      });
 
      var cancelButton = new JButton("Cancel");
      cancelButton.addActionListener(event -> dialog.setVisible(false));
 
      //添加按钮
 
      var 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;
 
      //拥有者框架
 
      Frame owner = null;
      if (parent instanceof Frame)
         owner = (Frame) parent;
      else
         owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);//返回给定组件的最先的父容器
 
      //第一次或改变拥有者,则创建新的对话框
 
      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;
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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;
   }
}

  

 

 

 

 

 

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

elipse IDE中调试运行教材556页程序12-21、12-2212-23,结合程序运行结果理解程序;

 掌握文件对话框的用法;

记录示例代码阅读理解中存在的问题与疑惑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
      });
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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);
 
      // set up menu bar
      var menuBar = new JMenuBar();//菜单栏
      setJMenuBar(menuBar);
 
      var menu = new JMenu("File");//菜单
      menuBar.add(menu);
 
      var 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();
            }
         });
 
      var exitItem = new JMenuItem("Exit");
      menu.add(exitItem);
      exitItem.addActionListener(event -> System.exit(0));
 
      //使用标签显示图像
      label = new JLabel();
      add(label);
 
      // 创建文件选择器
      chooser = new JFileChooser();
 
      //接受所有以.jpg, .jpeg, .gif格式的图片文件
      var 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")));//设置文件视图来提供文件过滤器显示信息
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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(100100));
      setBorder(BorderFactory.createEtchedBorder());//3D效果的直线边框
 
      chooser.addPropertyChangeListener(event -> {
         if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
         {
            //用户选定新的文件
            File f = (File) event.getNewValue();
            if (f == null)
            {
               setIcon(null);
               return;
            }
 
            //将图像设置未图标
            var icon = new ImageIcon(f.getPath());
 
            //图标过大或过小,缩放
            if (icon.getIconWidth() > getWidth())
               icon = new ImageIcon(icon.getImage().getScaledInstance(
                     getWidth(), -1, Image.SCALE_DEFAULT));
 
            setIcon(icon);//设置图标
         }
      });
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
   }
}

  

 

 

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

 elipse IDE中调试运行教材570页程序12-24,结合运行结果理解程序;

了解颜色选择器的用法。

记录示例代码阅读理解中存在的问题与疑惑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
      });
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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);
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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);
   }
 
   /**
    *弹出模式颜色选择器
    */
   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);//将当前选中的颜色,点击OK按钮,设置为背景颜色
      }
   }
 
   /**
    * 弹出无模式颜色选择器,点击OK,对话框的背景颜色就会被设置为所选择的颜色
    */
   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 */);
      }//点击OK,对话框的背景颜色就会被设置为所选择的颜色
 
      public void actionPerformed(ActionEvent event)
      {
         chooser.setColor(getBackground());
         dialog.setVisible(true);
      }
   }
 
   /**
    * 弹出无模式颜色选择器,当用户选择一种新的颜色,立即改变背景颜色
    */
   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) nullfalse /* not modal */);//无模式对话框
         dialog.add(chooser);
         dialog.pack();
      }
 
      public void actionPerformed(ActionEvent event)
      {
         chooser.setColor(getBackground());
         dialog.setVisible(true);
      }
   }
}

  

 

 

 

 

posted on 2019-12-09 20:26  夏热握火  阅读(217)  评论(1编辑  收藏  举报