201871010125-王玉江《面向對象程序設計(java)》第十五周學習總結
|
項目 |
內容 |
|
這個作業(yè)屬于哪個課程 |
<任課教師博客主頁鏈接> http://www.rzrgm.cn/nwnu-daizh/ |
|
這個作業(yè)的要求在哪里 |
<作業(yè)鏈接地址> http://www.rzrgm.cn/nwnu-daizh/p/11995615.html |
|
作業(yè)學習目標 |
(1) 掌握菜單組件用途及常用API; (2) 掌握對話框組件用途及常用API; (3) 學習設計簡單應用程序的GUI。 |
第一部分:總結菜單、對話框兩類組件用途及常用API(30分)
菜單是圖形用戶界面的重要組成部分,它通常有兩種使用方式:窗口菜單和快捷菜單。下面介紹窗口菜單的創(chuàng)建。
窗口菜單是由菜單條(MenmBar)、 菜單(Memu)、菜單項(Menltem)和復選菜單項CeckoMonultem等組成的。菜單放在菜單條里,菜單項放在菜單里。
(1)菜單條(MenBar)。
Java.awt包中的MenuBar類是負責創(chuàng)建菜單條的,即MenuBar類的一個實例就是一個菜單條。菜單條只能被添加到作為Frame對象中,整個菜單樹的根基。
Frame類有一個將菜單條放置到窗口中的方法:
setMenuBar (MenuBar bar)
該方法將菜單條添加到窗口的頂端,需要注意的是,只能向窗口添加一個菜單條。
例如:
MenuBar MenuBar1 = new MenuBar() //創(chuàng)建菜單條
setMenuBar (MenuBar1) //添加創(chuàng)建菜單條到Frame中
(2)菜單(Menu)。
Menu類負責創(chuàng)建菜單,即Menu類的一個實例就是一個菜單。 無法直接將菜單添加到容器的某位置,也無法使用布局管理器對其加以控制。菜單只能被添加到“菜單容器”菜單條(MenuBar) 中。
例如:
Menu Menu1=new Menu("文件") //創(chuàng)建菜單
menubar . add (Menu1) //添加到菜單條中
(3)菜單項(Menultem)。
MenuItem類是負責創(chuàng)建菜單項的,即MenuItem類的一個實例就是一個菜單項。菜單項必須添加到菜單中。MenuItem是整個“菜單樹”中的“葉子節(jié)點”。Menultem對象可以添加ActionListener,使其能完成相應的操作,在后面的章節(jié)中會學習相關知識。
例如:
MenuItem item1=new MenuItem ("新建") //創(chuàng)建菜單項
menul . add (item1) //添加到菜單中
工具欄:
工具欄中提供了快速執(zhí)行常用命令的按鈕,可以將它隨意拖拽到窗體的四周,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 狀態(tài),以確定當鼠標經過工具欄按鈕時,是否繪制按鈕的邊框,如果需要繪制則返回true,否則返回false
public void setFloatable(boolean b) : 設置Floatable 屬性,如果要移動工具欄,此屬性必須設置為true
.對話框
對話框分為模式對話框和無模對話框,模式對話框就是未處理此對話框之前不允許與其他窗口交互。
JOptionPane
提供了四個用靜態(tài)方法(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類
可以自己創(chuàng)建對話框,需調用超類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,可以創(chuàng)建和自 定義問題、信息、警告和錯誤等幾種類型的對 話框。
數據交換:輸入對話框含有供用戶輸入文本的文本框、一個確認和取 消按鈕,是有模式對話框。當輸入對話框可見時,要求用戶 輸入一個字符串。
文件對話框:專門用于對文件(或目錄)進行瀏覽和選擇的對 話框,常用的構造方法: – JFileChooser():根據用戶的缺省目錄創(chuàng)建文件對話框 – JFileChooser(File currentDirectory):根據File型參數 currentDirectory指定的目錄創(chuàng)建文件對話框
顏色對話框: javax.swing包中的JColorChooser類的靜態(tài)方 法: public static Color showDialog(Component component, String title, Color initialColor)創(chuàng)建一個顏色對話框
參數component指定對話框所依賴的組件,title 指定對話框的標題;initialColor 指定對話框返回 的初始顏色,即對話框消失后,返回的默認值。 顏色對話框可根據用戶在顏色對話框中選擇的顏 色返回一個顏色對象.
自己創(chuàng)建對話框,需調用超類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,結合運行結果理解程序;
掌握菜單的創(chuàng)建、菜單事件監(jiān)聽器、復選框和單選按鈕菜單項、彈出菜單以及快捷鍵和加速器的用法。
記錄示例代碼閱讀理解中存在的問題與疑惑。
|
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菜單項均可執(zhí)行點擊操作 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();//創(chuàng)建工具欄 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-15、12-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(); // 為每一個選項創(chuàng)建一個單選鈕 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(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); // 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來獲得這個靜態(tài)字段的值 } catch (Exception e) { return -1; } } /** * The action listener for the Show button shows a Confirm, Input, Message, or Option dialog * depending on the Type panel selection. */ private class ShowAction implements ActionListener { public void actionPerformed(ActionEvent event) { if (typePanel.getSelection().equals("Confirm")) JOptionPane.showConfirmDialog( OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel), getType(messageTypePanel)); else if (typePanel.getSelection().equals("Input")) { if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog( OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel)); else JOptionPane.showInputDialog(OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel), null, new String[] { "Yellow", "Blue", "Red" }, "Blue"); } else if (typePanel.getSelection().equals("Message")) JOptionPane.showMessageDialog( OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel)); else if (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog( OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel), getType(messageTypePanel), null, getOptions(), getOptions()[0]); } }}/** * A component with a painted surface */class SampleComponent extends JComponent{ public void paintComponent(Graphics g) { var g2 = (Graphics2D) g; var rect = new Rectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1); g2.setPaint(Color.YELLOW); g2.fill(rect); g2.setPaint(Color.BLUE); g2.draw(rect); } public Dimension getPreferredSize() { return new Dimension(10, 10); }} |



實驗1:測試程序4(7分)
在elipse IDE中調試運行教材552頁程序12-17、12-18,結合運行結果理解程序;
掌握對話框的創(chuàng)建方法;
記錄示例代碼閱讀理解中存在的問題與疑惑。
|
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); //創(chuàng)建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-19、12-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() { // 創(chuàng)建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);//含滾動條的文本區(qū) 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) { //第一次,創(chuàng)建對話框 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()); //創(chuàng)建還有user name與password域的面板 var panel = new JPanel(); panel.setLayout(new GridLayout(2, 2)); panel.add(new JLabel("User name:")); panel.add(username = new JTextField("")); panel.add(new JLabel("Password:")); panel.add(password = new JPasswordField("")); add(panel, BorderLayout.CENTER); // create Ok and Cancel buttons that terminate the dialog okButton = new JButton("Ok"); okButton.addActionListener(event -> { ok = true; dialog.setVisible(false);//點擊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);//返回給定組件的最先的父容器 //第一次或改變擁有者,則創(chuàng)建新的對話框 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); // 創(chuàng)建文件選擇器 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(100, 100)); 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()));//監(jiān)視顏色選擇,立即反饋給用戶 dialog = new JDialog((Frame) null, false /* not modal */);//無模式對話框 dialog.add(chooser); dialog.pack(); } public void actionPerformed(ActionEvent event) { chooser.setColor(getBackground()); dialog.setVisible(true); } }} |





浙公網安備 33010602011771號