SWIng使用者介面元件
2018面向物件程式設計(Java)第14周學習指導及要求(2018.11.29-2018.12.2)
學習目標
(1) 掌握GUI佈局管理器用法;
(2) 掌握各類Java Swing元件用途及常用API;
學習資源
1.教材第12章
2.第12章教學課件
3. corejava.zip
4. 實驗十四任務書
學習任務
1.增補《面向物件程式設計課程學習進度條》第十四周資料;
2.完成實驗十四;
3.將本週學習內容(包括實驗內容)通過部落格(隨筆)發表,部落格標題為“本人姓名《面向物件程式設計(java)》第十四周學習總結”。
4.本週學習總結需包含以下4部分:
1) 按佈局管理、文字輸入、選擇輸入、選單、對話方塊五個大類,分類總結各類元件的用途及核心API;
2) 總結第12章學習內容尚存在的問題;
3) 總結本週組內探究學習、組間協作學習的體會;
4) 提供組內探究學習的場景照片。
實驗——Swing圖形介面元件
1、實驗目的與要求
(1) 掌握GUI佈局管理器用法;
(2) 掌握各類Java Swing元件用途及常用API;
2、實驗內容和步驟
實驗1: 匯入第12章示例程式,測試程式並進行組內討論。
測試程式1
1.在elipse IDE中執行教材479頁程式12-1,結合執行結果理解程式;
2.掌握各種佈局管理器的用法;
3.理解GUI介面中事件處理技術的用途。
4.在佈局管理應用程式碼處添加註釋;
import java.awt.*; import javax.swing.*; public class Calculator { public static void main(String[] args) { EventQueue.invokeLater(() -> { CalculatorFrame frame = new CalculatorFrame(); frame.setTitle("Calculator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package calculator; import javax.swing.*; public class CalculatorFrame extends JFrame { public CalculatorFrame() { add(new CalculatorPanel()); pack(); } }
package calculator; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * 具有計算器按鈕和結果顯示的面板。 */ public class CalculatorPanel extends JPanel { private JButton display; private JPanel panel; private double result; private String lastCommand; private boolean start; public CalculatorPanel() { setLayout(new BorderLayout()); result = 0; lastCommand = "="; start = true; // 新增顯示 display = new JButton("0"); display.setEnabled(false); add(display, BorderLayout.NORTH); ActionListener insert = new InsertAction(); ActionListener command = new CommandAction(); panel = new JPanel(); panel.setLayout(new GridLayout(4, 4)); addButton("0", insert); addButton("1", insert); addButton("2", insert); addButton("3", command); addButton("4", insert); addButton("5", insert); addButton("6", insert); addButton("7", command); addButton("8", insert); addButton("9", insert); addButton("3", insert); addButton("/", command); addButton("*", insert); addButton(".", insert); addButton("=", command); addButton("+", command); add(panel, BorderLayout.SOUTH); // display = new JButton("驗證"); // display.setEnabled(true); // add(display, BorderLayout.CENTER); // // display = new JButton("驗證1"); // display.setEnabled(true); // add(display, BorderLayout.WEST); // // display = new JButton("驗證2"); // display.setEnabled(true); // add(display, BorderLayout.EAST); } /** * 向中心面板新增一個按鈕。 * @param 標籤的按鈕標籤 * @param 監聽器按鈕偵聽器 */ private void addButton(String label, ActionListener listener) { JButton button = new JButton(label); button.addActionListener(listener); panel.add(button); } /** * 此操作將按鈕操作字串插入到顯示文字的末尾 */ private class InsertAction implements ActionListener { public void actionPerformed(ActionEvent event) { String input = event.getActionCommand(); if (start) { display.setText(""); start = false; } display.setText(display.getText() + input); } } /** * 此操作執行按鈕操作字串所表示的命令。 */ private class CommandAction implements ActionListener { public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (start) { if (command.equals("-")) { display.setText(command); start = false; } else lastCommand = command; } else { calculate(Double.parseDouble(display.getText())); lastCommand = command; start = true; } } } /** * 執行懸而未決的計算。 * @param x值與先前結果一起累積。 */ public void calculate(double x) { if (lastCommand.equals("+")) result += x; else if (lastCommand.equals("-")) result -= x; else if (lastCommand.equals("*")) result *= x; else if (lastCommand.equals("/")) result /= x; else if (lastCommand.equals("=")) result = x; display.setText("" + result); } }
測試程式2
1.在elipse IDE中除錯執行教材486頁程式12-2,結合執行結果理解程式;
2.掌握各種文字元件的用法;
3.記錄示例程式碼閱讀理解中存在的問題與疑惑。
package text; import java.awt.*; import javax.swing.*; /** * @version 1.41 2015-06-12 * @author Cay Horstmann */ public class TextComponentTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new TextComponentFrame(); frame.setTitle("TextComponentTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package text; import java.awt.BorderLayout; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; /** * 具有文字文字元件的框架. */ public class TextComponentFrame extends JFrame { public static final int TEXTAREA_ROWS = 8; public static final int TEXTAREA_COLUMNS = 20; public TextComponentFrame() { JTextField textField = new JTextField(); JPasswordField passwordField = new JPasswordField(); JPanel northPanel = new JPanel(); northPanel.setLayout(new GridLayout(2, 2)); northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT)); northPanel.add(textField); northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT)); northPanel.add(passwordField); add(northPanel, BorderLayout.NORTH); JTextArea textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS); JScrollPane scrollPane = new JScrollPane(textArea); add(scrollPane, BorderLayout.CENTER); // 新增按鈕將文字追加到文字區域 JPanel southPanel = new JPanel(); JButton insertButton = new JButton("Insert"); southPanel.add(insertButton); insertButton.addActionListener(event -> textArea.append("User name: " + textField.getText() + " Password: " + new String(passwordField.getPassword()) + "\n")); add(southPanel, BorderLayout.SOUTH); pack(); } }
測試程式3
1.在elipse IDE中除錯執行教材489頁程式12-3,結合執行結果理解程式;
2.掌握複選框元件的用法;
3.記錄示例程式碼閱讀理解中存在的問題與疑惑。
package checkBox; import java.awt.*; import javax.swing.*; /** * @version 1.34 2015-06-12 * @author Cay Horstmann */ public class CheckBoxTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new CheckBoxFrame(); frame.setTitle("CheckBoxTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package checkBox; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * 帶有樣本文字標籤的框和用於選擇字型的複選框 * attributes. */ public class CheckBoxFrame extends JFrame { private JLabel label; private JCheckBox bold; private JCheckBox italic; private static final int FONTSIZE = 24; public CheckBoxFrame() { // 新增示例文字標籤 label = new JLabel("The quick brown fox jumps over the lazy dog."); label.setFont(new Font("Serif", Font.BOLD, FONTSIZE)); add(label, BorderLayout.CENTER); // 此偵聽器設定字型屬性 // 到複選框狀態的標籤 ActionListener listener = event -> { int mode = 0; if (bold.isSelected()) mode += Font.BOLD; if (italic.isSelected()) mode += Font.ITALIC; label.setFont(new Font("Serif", mode, FONTSIZE)); }; // 新增複選框 JPanel buttonPanel = new JPanel(); bold = new JCheckBox("Bold"); bold.addActionListener(listener); bold.setSelected(true); buttonPanel.add(bold); italic = new JCheckBox("Italic"); italic.addActionListener(listener); buttonPanel.add(italic); add(buttonPanel, BorderLayout.SOUTH); pack(); } }
測試程式4
1.在elipse IDE中除錯執行教材491頁程式12-4,執行結果理解程式;
2.掌握單選按鈕元件的用法;
3.記錄示例程式碼閱讀理解中存在的問題與疑惑。
package radioButton; import java.awt.*; import javax.swing.*; /** * @version 1.34 2015-06-12 * @author Cay Horstmann */ public class RadioButtonTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new RadioButtonFrame(); frame.setTitle("RadioButtonTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package radioButton; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * 帶有樣本文字標籤和單選按鈕以選擇字型大小的框架。 */ public class RadioButtonFrame extends JFrame { private JPanel buttonPanel; private ButtonGroup group; private JLabel label; private static final int DEFAULT_SIZE = 36; public RadioButtonFrame() { // 新增示例文字標籤 label = new JLabel("The quick brown fox jumps over the lazy dog."); label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE)); add(label, BorderLayout.CENTER); // 新增單選按鈕 buttonPanel = new JPanel(); group = new ButtonGroup(); addRadioButton("Small", 8); addRadioButton("Medium", 12); addRadioButton("Large", 18); addRadioButton("Extra large", 36); add(buttonPanel, BorderLayout.SOUTH); pack(); } /** * 新增一個設定示例文字字型大小的單選按鈕。 * @param 命名按鈕上出現的字串 * @param 設定此按鈕設定的字型大小 */ public void addRadioButton(String name, int size) { boolean selected = size == DEFAULT_SIZE; JRadioButton button = new JRadioButton(name, selected); group.add(button); buttonPanel.add(button); // 此偵聽器設定標籤字型大小。 ActionListener listener = event -> label.setFont(new Font("Serif", Font.PLAIN, size)); button.addActionListener(listener); } }
測試程式5
1.在elipse IDE中除錯執行教材494頁程式12-5,結合執行結果理解程式;
2.掌握邊框的用法;
3。記錄示例程式碼閱讀理解中存在的問題與疑惑。
package border; import java.awt.*; import javax.swing.*; /** * @version 1.34 2015-06-13 * @author Cay Horstmann */ public class BorderTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new BorderFrame(); frame.setTitle("BorderTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package border; import java.awt.*; import javax.swing.*; import javax.swing.border.*; /** * 用單選按鈕選擇邊框樣式的框架 */ public class BorderFrame extends JFrame { private JPanel demoPanel; private JPanel buttonPanel; private ButtonGroup group; public BorderFrame() { demoPanel = new JPanel(); buttonPanel = new JPanel(); group = new ButtonGroup(); addRadioButton("Lowered bevel", BorderFactory.createLoweredBevelBorder()); addRadioButton("Raised bevel", BorderFactory.createRaisedBevelBorder()); addRadioButton("Etched", BorderFactory.createEtchedBorder()); addRadioButton("Line", BorderFactory.createLineBorder(Color.BLUE)); addRadioButton("Matte", BorderFactory.createMatteBorder(10, 10, 10, 10, Color.BLUE)); addRadioButton("Empty", BorderFactory.createEmptyBorder()); Border etched = BorderFactory.createEtchedBorder(); Border titled = BorderFactory.createTitledBorder(etched, "Border types"); buttonPanel.setBorder(titled); setLayout(new GridLayout(2, 1)); add(buttonPanel); add(demoPanel); pack(); } public void addRadioButton(String buttonName, Border b) { JRadioButton button = new JRadioButton(buttonName); button.addActionListener(event -> demoPanel.setBorder(b)); group.add(button); buttonPanel.add(button); } }
測試程式6
1.在elipse IDE中除錯執行教材498頁程式12-6,結合執行結果理解程式;
2.掌握組合框元件的用法;
3.記錄示例程式碼閱讀理解中存在的問題與疑惑。
package comboBox; import java.awt.*; import javax.swing.*; /** * @version 1.35 2015-06-12 * @author Cay Horstmann */ public class ComboBoxTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new ComboBoxFrame(); frame.setTitle("ComboBoxTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package comboBox; import java.awt.BorderLayout; import java.awt.Font; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; /** * 具有樣本文字標籤和選擇字體面的組合框的框架。 */ public class ComboBoxFrame extends JFrame { private JComboBox<String> faceCombo; private JLabel label; private static final int DEFAULT_SIZE = 24; public ComboBoxFrame() { // 新增示例文字標籤 label = new JLabel("The quick brown fox jumps over the lazy dog."); label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE)); add(label, BorderLayout.CENTER); // 製作組合框並新增面部名稱 faceCombo = new JComboBox<>(); faceCombo.addItem("Serif"); faceCombo.addItem("SansSerif"); faceCombo.addItem("Monospaced"); faceCombo.addItem("Dialog"); faceCombo.addItem("DialogInput"); // 組合框偵聽器將標籤字型更改為選定的面部名稱。 faceCombo.addActionListener(event -> label.setFont( new Font(faceCombo.getItemAt(faceCombo.getSelectedIndex()), Font.PLAIN, DEFAULT_SIZE))); // 將組合框新增到框架的南部邊界的面板上 JPanel comboPanel = new JPanel(); comboPanel.add(faceCombo); add(comboPanel, BorderLayout.SOUTH); pack(); } }
測試程式7
1.在elipse IDE中除錯執行教材501頁程式12-7,結合執行結果理解程式;
2.掌握滑動條元件的用法;
3.記錄示例程式碼閱讀理解中存在的問題與疑惑。
package slider; import java.awt.*; import javax.swing.*; /** * @version 1.15 2015-06-12 * @author Cay Horstmann */ public class SliderTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { SliderFrame frame = new SliderFrame(); frame.setTitle("SliderTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package slider; import java.awt.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; /** * 一個具有許多滑塊和文字欄位的滑塊值的框架。 */ public class SliderFrame extends JFrame { private JPanel sliderPanel; private JTextField textField; private ChangeListener listener; public SliderFrame() { sliderPanel = new JPanel(); sliderPanel.setLayout(new GridBagLayout()); // 所有滑塊的公用偵聽器 listener = event -> { // 當滑塊值改變時更新文字欄位 JSlider source = (JSlider) event.getSource(); textField.setText("" + source.getValue()); }; // 新增普通滑塊 JSlider slider = new JSlider(); addSlider(slider, "Plain"); // 新增有主和小蜱的滑塊 slider = new JSlider(); slider.setPaintTicks(true); slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(5); addSlider(slider, "Ticks"); // 新增一個滑動到滴答的滑塊 slider = new JSlider(); slider.setPaintTicks(true); slider.setSnapToTicks(true); slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(5); addSlider(slider, "Snap to ticks"); // 新增沒有磁軌的滑塊 slider = new JSlider(); slider.setPaintTicks(true); slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(5); slider.setPaintTrack(false); addSlider(slider, "No track"); // 新增倒置滑塊 slider = new JSlider(); slider.setPaintTicks(true); slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(5); slider.setInverted(true); addSlider(slider, "Inverted"); // 新增帶有數字標籤的滑塊 slider = new JSlider(); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(5); addSlider(slider, "Labels"); // 新增帶有字母標籤的滑塊 slider = new JSlider(); slider.setPaintLabels(true); slider.setPaintTicks(true); slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(5); Dictionary<Integer, Component> labelTable = new Hashtable<>(); labelTable.put(0, new JLabel("A")); labelTable.put(20, new JLabel("B")); labelTable.put(40, new JLabel("C")); labelTable.put(60, new JLabel("D")); labelTable.put(80, new JLabel("E")); labelTable.put(100, new JLabel("F")); slider.setLabelTable(labelTable); addSlider(slider, "Custom labels"); // 新增帶有圖示標籤的滑塊 slider = new JSlider(); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.setSnapToTicks(true); slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(20); labelTable = new Hashtable<Integer, Component>(); // 新增卡片影象 labelTable.put(0, new JLabel(new ImageIcon("nine.gif"))); labelTable.put(20, new JLabel(new ImageIcon("ten.gif"))); labelTable.put(40, new JLabel(new ImageIcon("jack.gif"))); labelTable.put(60, new JLabel(new ImageIcon("queen.gif"))); labelTable.put(80, new JLabel(new ImageIcon("king.gif"))); labelTable.put(100, new JLabel(new ImageIcon("ace.gif"))); slider.setLabelTable(labelTable); addSlider(slider, "Icon labels"); // 新增顯示滑塊值的文字欄位 textField = new JTextField(); add(sliderPanel, BorderLayout.CENTER); add(textField, BorderLayout.SOUTH); pack(); } /** * 向滑塊面板新增滑塊並鉤住聽者 * @param S滑塊 * @param 描述滑塊描述 */ public void addSlider(JSlider s, String description) { s.addChangeListener(listener); JPanel panel = new JPanel(); panel.add(s); panel.add(new JLabel(description)); panel.setAlignmentX(Component.LEFT_ALIGNMENT); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridy = sliderPanel.getComponentCount(); gbc.anchor = GridBagConstraints.WEST; sliderPanel.add(panel, gbc); } }
測試程式8
1.在elipse IDE中除錯執行教材512頁程式12-8,結合執行結果理解程式;
2.掌握選單的建立、選單事件監聽器、複選框和單選按鈕選單項、彈出選單以及快捷鍵和加速器的用法。
3.記錄示例程式碼閱讀理解中存在的問題與疑惑。
package menu; import java.awt.*; import javax.swing.*; /** * @version 1.24 2012-06-12 * @author Cay Horstmann */ public class MenuTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new MenuFrame(); frame.setTitle("MenuTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package menu; import java.awt.event.*; import javax.swing.*; /** * 一個帶有示例選單欄的框架。 */ 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; /** * 將動作名稱列印到Studio.OUT的示例動作。 */ class TestAction extends AbstractAction { public TestAction(String name) { super(name); } public void actionPerformed(ActionEvent event) { System.out.println(getValue(Action.NAME) + " selected."); } } public MenuFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); JMenu fileMenu = new JMenu("File"); fileMenu.add(new TestAction("New")); // 演示加速器 JMenuItem openItem = fileMenu.add(new TestAction("Open")); openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O")); fileMenu.addSeparator(); saveAction = new TestAction("Save"); JMenuItem saveItem = fileMenu.add(saveAction); saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S")); saveAsAction = new TestAction("Save As"); fileMenu.add(saveAsAction); fileMenu.addSeparator(); 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); saveAsAction.setEnabled(saveOk); } }); ButtonGroup group = new ButtonGroup(); JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert"); insertItem.setSelected(true); JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype"); group.add(insertItem); group.add(overtypeItem); // 演示圖示 Action cutAction = new TestAction("Cut"); cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif")); Action copyAction = new TestAction("Copy"); copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif")); Action pasteAction = new TestAction("Paste"); pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif")); JMenu editMenu = new JMenu("Edit"); editMenu.add(cutAction); editMenu.add(copyAction); editMenu.add(pasteAction); // 演示巢狀選單 JMenu optionMenu = new JMenu("Options"); optionMenu.add(readonlyItem); optionMenu.addSeparator(); optionMenu.add(insertItem); optionMenu.add(overtypeItem); editMenu.addSeparator(); editMenu.add(optionMenu); // 助記符演示 JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('H'); JMenuItem indexItem = new JMenuItem("Index"); indexItem.setMnemonic('I'); helpMenu.add(indexItem); // 還可以將助記鍵新增到動作中。 Action aboutAction = new TestAction("About"); aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A')); helpMenu.add(aboutAction); // 將所有頂級選單新增到選單欄 JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(helpMenu); // 演示彈出視窗 popup = new JPopupMenu(); popup.add(cutAction); popup.add(copyAction); popup.add(pasteAction); JPanel panel = new JPanel(); panel.setComponentPopupMenu(popup); add(panel); } }
測試程式9
1.在elipse IDE中除錯執行教材517頁程式12-9,結合執行結果理解程式;
2.掌握工具欄和工具提示的用法;
3.記錄示例程式碼閱讀理解中存在的問題與疑惑。
package toolBar; import java.awt.*; import javax.swing.*; /** * @version 1.14 2015-06-12 * @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.*; /** * 帶有工具欄和選單的框架,用於顏色變化。 */ 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); // 新增顏色變化面板 panel = new JPanel(); add(panel, BorderLayout.CENTER); // 設定動作 Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE); Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"), Color.YELLOW); Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); Action exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif")) { public void actionPerformed(ActionEvent event) { System.exit(0); } }; exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit"); // 填充工具欄 JToolBar bar = new JToolBar(); bar.add(blueAction); bar.add(yellowAction); bar.add(redAction); bar.addSeparator(); bar.add(exitAction); add(bar, BorderLayout.NORTH); // 填充選單 JMenu menu = new JMenu("Color"); menu.add(yellowAction); menu.add(blueAction); menu.add(redAction); menu.add(exitAction); JMenuBar menuBar = new JMenuBar(); menuBar.add(menu); setJMenuBar(menuBar); } /** * 顏色動作將幀的背景設定為給定的顏色。 */ class ColorAction extends AbstractAction { public ColorAction(String name, Icon icon, Color c) { putValue(Action.NAME, name); putValue(Action.SMALL_ICON, icon); putValue(Action.SHORT_DESCRIPTION, name + " background"); putValue("Color", c); } public void actionPerformed(ActionEvent event) { Color c = (Color) getValue("Color"); panel.setBackground(c); } } }
測試程式10
1.在elipse IDE中除錯執行教材524頁程式12-10、12-11,結合執行結果理解程式,瞭解GridbagLayout的用法。
2.在elipse IDE中除錯執行教材533頁程式12-12,結合程式執行結果理解程式,瞭解GroupLayout的用法。
3.記錄示例程式碼閱讀理解中存在的問題與疑惑。
package gridbag; import java.awt.EventQueue; import javax.swing.JFrame; /** * @version 1.35 2015-06-12 * @author Cay Horstmann */ public class GridBagLayoutTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new FontFrame(); frame.setTitle("GridBagLayoutTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package gridbag; import java.awt.*; /** * This class simplifies the use of the GridBagConstraints class. * @version 1.01 2004-05-06 * @author Cay Horstmann */ public class GBC extends GridBagConstraints { /** * Constructs a GBC with a given gridx and gridy position and all other grid * bag constraint values set to the default. * @param gridx the gridx position * @param gridy the gridy position */ public GBC(int gridx, int gridy) { this.gridx = gridx; this.gridy = gridy; } /** * Constructs a GBC with given gridx, gridy, gridwidth, gridheight and all * other grid bag constraint values set to the default. * @param gridx the gridx position * @param gridy the gridy position * @param gridwidth the cell span in x-direction * @param gridheight the cell span in y-direction */ public GBC(int gridx, int gridy, int gridwidth, int gridheight) { this.gridx = gridx; this.gridy = gridy; this.gridwidth = gridwidth; this.gridheight = gridheight; } /** * Sets the anchor. * @param anchor the anchor value * @return this object for further modification */ public GBC setAnchor(int anchor) { this.anchor = anchor; return this; } /** * Sets the fill direction. * @param fill the fill direction * @return this object for further modification */ public GBC setFill(int fill) { this.fill = fill; return this; } /** * Sets the cell weights. * @param weightx the cell weight in x-direction * @param weighty the cell weight in y-direction * @return this object for further modification */ public GBC setWeight(double weightx, double weighty) { this.weightx = weightx; this.weighty = weighty; return this; } /** * Sets the insets of this cell. * @param distance the spacing to use in all directions * @return this object for further modification */ public GBC setInsets(int distance) { this.insets = new Insets(distance, distance, distance, distance); return this; } /** * Sets the insets of this cell. * @param top the spacing to use on top * @param left the spacing to use to the left * @param bottom the spacing to use on the bottom * @param right the spacing to use to the right * @return this object for further modification */ public GBC setInsets(int top, int left, int bottom, int right) { this.insets = new Insets(top, left, bottom, right); return this; } /** * Sets the internal padding * @param ipadx the internal padding in x-direction * @param ipady the internal padding in y-direction * @return this object for further modification */ public GBC setIpad(int ipadx, int ipady) { this.ipadx = ipadx; this.ipady = ipady; return this; } }
package gridbag; import java.awt.Font; import java.awt.GridBagLayout; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; /** * A frame that uses a grid bag layout to arrange font selection components. */ public class FontFrame extends JFrame { public static final int TEXT_ROWS = 10; public static final int TEXT_COLUMNS = 20; private JComboBox<String> face; private JComboBox<Integer> size; private JCheckBox bold; private JCheckBox italic; private JTextArea sample; public FontFrame() { GridBagLayout layout = new GridBagLayout(); setLayout(layout); ActionListener listener = event -> updateSample(); // construct components JLabel faceLabel = new JLabel("Face: "); face = new JComboBox<>(new String[] { "Serif", "SansSerif", "Monospaced", "Dialog", "DialogInput" }); face.addActionListener(listener); JLabel sizeLabel = new JLabel("Size: "); size = new JComboBox<>(new Integer[] { 8, 10, 12, 15, 18, 24, 36, 48 }); size.addActionListener(listener); bold = new JCheckBox("Bold"); bold.addActionListener(listener); italic = new JCheckBox("Italic"); italic.addActionListener(listener); sample = new JTextArea(TEXT_ROWS, TEXT_COLUMNS); sample.setText("The quick brown fox jumps over the lazy dog"); sample.setEditable(false); sample.setLineWrap(true); sample.setBorder(BorderFactory.createEtchedBorder()); // add components to grid, using GBC convenience class add(faceLabel, new GBC(0, 0).setAnchor(GBC.EAST)); add(face, new GBC(1, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0) .setInsets(1)); add(sizeLabel, new GBC(0, 1).setAnchor(GBC.EAST)); add(size, new GBC(1, 1).setFill(GBC.HORIZONTAL).setWeight(100, 0) .setInsets(1)); add(bold, new GBC(0, 2, 2, 1).setAnchor(GBC.CENTER).setWeight(100, 100)); add(italic, new GBC(0, 3, 2, 1).setAnchor(GBC.CENTER).setWeight(100, 100)); add(sample, new GBC(2, 0, 1, 4).setFill(GBC.BOTH).setWeight(100, 100)); pack(); updateSample(); } public void updateSample() { String fontFace = (String) face.getSelectedItem(); int fontStyle = (bold.isSelected() ? Font.BOLD : 0) + (italic.isSelected() ? Font.ITALIC : 0); int fontSize = size.getItemAt(size.getSelectedIndex()); Font font = new Font(fontFace, fontStyle, fontSize); sample.setFont(font); sample.repaint(); } }
package groupLayout; import java.awt.EventQueue; import javax.swing.JFrame; /** * @version 1.01 2015-06-12 * @author Cay Horstmann */ public class GroupLayoutTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new FontFrame(); frame.setTitle("GroupLayoutTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package groupLayout; import java.awt.Font; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.GroupLayout; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.LayoutStyle; import javax.swing.SwingConstants; /** * A frame that uses a group layout to arrange font selection components. */ public class FontFrame extends JFrame { public static final int TEXT_ROWS = 10; public static final int TEXT_COLUMNS = 20; private JComboBox<String> face; private JComboBox<Integer> size; private JCheckBox bold; private JCheckBox italic; private JScrollPane pane; private JTextArea sample; public FontFrame() { ActionListener listener = event -> updateSample(); // construct components JLabel faceLabel = new JLabel("Face: "); face = new JComboBox<>(new String[] { "Serif", "SansSerif", "Monospaced", "Dialog", "DialogInput" }); face.addActionListener(listener); JLabel sizeLabel = new JLabel("Size: "); size = new JComboBox<>(new Integer[] { 8, 10, 12, 15, 18, 24, 36, 48 }); size.addActionListener(listener); bold = new JCheckBox("Bold"); bold.addActionListener(listener); italic = new JCheckBox("Italic"); italic.addActionListener(listener); sample = new JTextArea(TEXT_ROWS, TEXT_COLUMNS); sample.setText("The quick brown fox jumps over the lazy dog"); sample.setEditable(false); sample.setLineWrap(true); sample.setBorder(BorderFactory.createEtchedBorder()); pane = new JScrollPane(sample); GroupLayout layout = new GroupLayout(getContentPane()); setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup().addContainerGap().addGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGroup( layout.createParallelGroup(GroupLayout.Alignment.TRAILING) .addComponent(faceLabel).addComponent(sizeLabel)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING, false) .addComponent(size).addComponent(face))) .addComponent(italic).addComponent(bold)).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addComponent(pane) .addContainerGap())); layout.linkSize(SwingConstants.HORIZONTAL, new java.awt.Component[] { face, size }); layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup().addContainerGap().addGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent( pane, GroupLayout.Alignment.TRAILING).addGroup( layout.createSequentialGroup().addGroup( layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(face).addComponent(faceLabel)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent(size) .addComponent(sizeLabel)).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addComponent( italic, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(bold, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap())); pack(); } public void updateSample() { String fontFace = (String) face.getSelectedItem(); int fontStyle = (bold.isSelected() ? Font.BOLD : 0) + (italic.isSelected() ? Font.ITALIC : 0); int fontSize = size.getItemAt(size.getSelectedIndex()); Font font = new Font(fontFace, fontStyle, fontSize); sample.setFont(font); sample.repaint(); } }
測試程式11
1.在elipse IDE中除錯執行教材539頁程式12-13、12-14,結合執行結果理解程式;
2.掌握定製佈局管理器的用法。
3.記錄示例程式碼閱讀理解中存在的問題與疑惑。
package circleLayout; import java.awt.*; import javax.swing.*; /** * @version 1.33 2015-06-12 * @author Cay Horstmann */ public class CircleLayoutTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new CircleLayoutFrame(); frame.setTitle("CircleLayoutTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package circleLayout; import javax.swing.*; /** * A frame that shows buttons arranged along a circle. */ public class CircleLayoutFrame extends