201771010102 常惠琢 2018面向物件程式設計(Java)第14周學習總結
1 package gridbag; 2 3 import java.awt.*; 4 5 /** 6 * This class simplifies the use of the GridBagConstraints class. 7 * @version 1.01 2004-05-06 8 * @author Cay Horstmann 9 */ 10 public class GBC extends GridBagConstraints 11 { 12 /** 13 * Constructs a GBC with a given gridx and gridy position and all other grid14 * bag constraint values set to the default. 15 * @param gridx the gridx position 16 * @param gridy the gridy position 17 */ 18 public GBC(int gridx, int gridy) 19 { 20 this.gridx = gridx; 21 this.gridy = gridy; 22 } 23 24 /** 25 * Constructs a GBC with given gridx, gridy, gridwidth, gridheight and all26 * other grid bag constraint values set to the default. 27 * @param gridx the gridx position 28 * @param gridy the gridy position 29 * @param gridwidth the cell span in x-direction 30 * @param gridheight the cell span in y-direction 31 */ 32 public GBC(int gridx, intgridy, int gridwidth, int gridheight) 33 { 34 this.gridx = gridx; 35 this.gridy = gridy; 36 this.gridwidth = gridwidth; 37 this.gridheight = gridheight; 38 } 39 40 /** 41 * Sets the anchor. 42 * @param anchor the anchor value 43 * @return this object for further modification 44 */ 45 public GBC setAnchor(int anchor) 46 { 47 this.anchor = anchor; 48 return this; 49 } 50 51 /** 52 * Sets the fill direction. 53 * @param fill the fill direction 54 * @return this object for further modification 55 */ 56 public GBC setFill(int fill) 57 { 58 this.fill = fill; 59 return this; 60 } 61 62 /** 63 * Sets the cell weights. 64 * @param weightx the cell weight in x-direction 65 * @param weighty the cell weight in y-direction 66 * @return this object for further modification 67 */ 68 public GBC setWeight(double weightx, double weighty) 69 { 70 this.weightx = weightx; 71 this.weighty = weighty; 72 return this; 73 } 74 75 /** 76 * Sets the insets of this cell. 77 * @param distance the spacing to use in all directions 78 * @return this object for further modification 79 */ 80 public GBC setInsets(int distance) 81 { 82 this.insets = new Insets(distance, distance, distance, distance); 83 return this; 84 } 85 86 /** 87 * Sets the insets of this cell. 88 * @param top the spacing to use on top 89 * @param left the spacing to use to the left 90 * @param bottom the spacing to use on the bottom 91 * @param right the spacing to use to the right 92 * @return this object for further modification 93 */ 94 public GBC setInsets(int top, int left, int bottom, int right) 95 { 96 this.insets = new Insets(top, left, bottom, right); 97 return this; 98 } 99 100 /** 101 * Sets the internal padding 102 * @param ipadx the internal padding in x-direction 103 * @param ipady the internal padding in y-direction 104 * @return this object for further modification 105 */ 106 public GBC setIpad(int ipadx, int ipady) 107 { 108 this.ipadx = ipadx; 109 this.ipady = ipady; 110 return this; 111 } 112 }
實驗十四 Swing圖形介面元件
實驗時間 20178-11-29
1、實驗目的與要求
(1) 掌握GUI佈局管理器用法;
(2) 掌握各類Java Swing元件用途及常用API;
2、實驗內容和步驟
實驗1: 匯入第12章示例程式,測試程式並進行組內討論。
測試程式1
l 在elipse IDE中執行教材479頁程式12-1,結合執行結果理解程式;
l 掌握各種佈局管理器的用法;
l 理解GUI介面中事件處理技術的用途。
l 在佈局管理應用程式碼處添加註釋;
package calculator; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * A panel with calculator buttons and a result display. */ 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; // add the display display = new JButton("0"); display.setEnabled(false); add(display, BorderLayout.NORTH); ActionListener insert = new InsertAction(); ActionListener command = new CommandAction(); // add the buttons in a 4 x 4 grid panel = new JPanel(); panel.setLayout(new GridLayout(4, 4)); addButton("3", insert); addButton("6", insert); addButton("9", insert);//數字用insert addButton("+", command);//命令用command addButton("2", insert); addButton("5", insert); addButton("8", insert); addButton("-", command); addButton("1", insert); addButton("4", insert); addButton("7", insert); addButton("*", command); addButton("0", insert); addButton(".", insert); addButton("=", command); addButton("/", command); add(panel, BorderLayout.CENTER); //add(display, BorderLayout.NORTH);CENTER JButton b1 = new JButton("驗證"); add(b1,BorderLayout.SOUTH); JButton br = new JButton("驗證1"); add(br,BorderLayout.WEST); JButton b2 = new JButton("驗證2"); add(b2,BorderLayout.EAST); } /** * Adds a button to the center panel. * @param label the button label * @param listener the button listener */ private void addButton(String label, ActionListener listener) { JButton button = new JButton(label); button.addActionListener(listener); panel.add(button); } /** * This action inserts the button action string to the end of the display text. */ 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); } } /** * This action executes the command that the button action string denotes. */ 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()));//用parseDouble把字串轉換成對應的資料 lastCommand = command; start = true; } } } /** * Carries out the pending calculation. * @param x the value to be accumulated with the prior result. */ 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);//display的更改器方法;""會吧result轉換成字串資料 } }
1 package colorChooser; 2 3 import javax.swing.*; 4 5 /** 6 * A frame with a color chooser panel 7 */ 8 public class ColorChooserFrame extends JFrame 9 { 10 private static final int DEFAULT_WIDTH = 300; 11 private static final int DEFAULT_HEIGHT = 200; 12 13 public ColorChooserFrame() 14 { 15 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 16 17 // add color chooser panel to frame 18 19 ColorChooserPanel panel = new ColorChooserPanel(); 20 add(panel); 21 } 22 }
1 package colorChooser; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.04 2015-06-12 8 * @author Cay Horstmann 9 */ 10 public class ColorChooserTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 JFrame frame = new ColorChooserFrame(); 16 frame.setTitle("ColorChooserTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
測試程式2
l 在elipse IDE中除錯執行教材486頁程式12-2,結合執行結果理解程式;
l 掌握各種文字元件的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
1 package text; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.41 2015-06-12 8 * @author Cay Horstmann 9 */ 10 public class TextComponentTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 JFrame frame = new TextComponentFrame(); 16 frame.setTitle("TextComponentTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
1 package text; 2 3 import java.awt.BorderLayout; 4 import java.awt.GridLayout; 5 6 import javax.swing.JButton; 7 import javax.swing.JFrame; 8 import javax.swing.JLabel; 9 import javax.swing.JPanel; 10 import javax.swing.JPasswordField; 11 import javax.swing.JScrollPane; 12 import javax.swing.JTextArea; 13 import javax.swing.JTextField; 14 import javax.swing.SwingConstants; 15 16 /** 17 * A frame with sample text components. 18 */ 19 public class TextComponentFrame extends JFrame 20 { 21 public static final int TEXTAREA_ROWS = 8; 22 public static final int TEXTAREA_COLUMNS = 20; 23 24 public TextComponentFrame() 25 { 26 JTextField textField = new JTextField(); 27 JPasswordField passwordField = new JPasswordField(); 28 29 JPanel northPanel = new JPanel(); 30 northPanel.setLayout(new GridLayout(2, 2)); 31 northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT)); 32 northPanel.add(textField); 33 northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT)); 34 northPanel.add(passwordField); 35 36 add(northPanel, BorderLayout.NORTH); 37 38 JTextArea textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS); 39 JScrollPane scrollPane = new JScrollPane(textArea); 40 41 add(scrollPane, BorderLayout.CENTER); 42 43 // add button to append text into the text area 44 45 JPanel southPanel = new JPanel(); 46 47 JButton insertButton = new JButton("Insert"); 48 southPanel.add(insertButton); 49 insertButton.addActionListener(event -> 50 textArea.append("User name: " + textField.getText() + " Password: " 51 + new String(passwordField.getPassword()) + "\n")); 52 53 add(southPanel, BorderLayout.SOUTH); 54 pack(); 55 } 56 }
測試程式3
l 在elipse IDE中除錯執行教材489頁程式12-3,結合執行結果理解程式;
l 掌握複選框元件的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
1 package checkBox; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 /** 8 * A frame with a sample text label and check boxes for selecting font 9 * attributes. 10 */ 11 public class CheckBoxFrame extends JFrame 12 { 13 private JLabel label; 14 private JCheckBox bold; 15 private JCheckBox italic; 16 private static final int FONTSIZE = 24; 17 18 public CheckBoxFrame() 19 { 20 // add the sample text label 21 22 label = new JLabel("ijnjoijojoippkp[kpiooijoijnnjnoi-=0"); 23 label.setFont(new Font("Serif", Font.BOLD, FONTSIZE)); 24 add(label, BorderLayout.CENTER); 25 26 // this listener sets the font attribute of 27 // the label to the check box state 28 29 ActionListener listener = event -> { 30 int mode = 0; 31 if (bold.isSelected()) mode += Font.BOLD; 32 if (italic.isSelected()) mode += Font.ITALIC; 33 label.setFont(new Font("Serif", mode, FONTSIZE)); 34 }; 35 36 // add the check boxes 37 38 JPanel buttonPanel = new JPanel(); 39 40 bold = new JCheckBox("Bold"); 41 bold.addActionListener(listener); 42 bold.setSelected(true); 43 buttonPanel.add(bold); 44 45 italic = new JCheckBox("Italic"); 46 italic.addActionListener(listener); 47 buttonPanel.add(italic); 48 49 add(buttonPanel, BorderLayout.SOUTH); 50 pack(); 51 } 52 }
1 package checkBox; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.34 2015-06-12 8 * @author Cay Horstmann 9 */ 10 public class CheckBoxTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 JFrame frame = new CheckBoxFrame(); 16 frame.setTitle("CheckBoxTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
測試程式4
l 在elipse IDE中除錯執行教材491頁程式12-4,執行結果理解程式;
l 掌握單選按鈕元件的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
1 package radioButton; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 /** 8 * A frame with a sample text label and radio buttons for selecting font sizes. 9 */ 10 public class RadioButtonFrame extends JFrame 11 { 12 private JPanel buttonPanel; 13 private ButtonGroup group; 14 private JLabel label; 15 private static final int DEFAULT_SIZE = 36; 16 17 public RadioButtonFrame() 18 { 19 // add the sample text label 20 21 label = new JLabel("The quick brown fox jumps over the lazy dog."); 22 label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE)); 23 add(label, BorderLayout.CENTER); 24 25 // add the radio buttons 26 27 buttonPanel = new JPanel(); 28 group = new ButtonGroup(); 29 30 addRadioButton("Small", 8); 31 addRadioButton("Medium", 12); 32 addRadioButton("Large", 18); 33 addRadioButton("Extra large", 36); 34 35 add(buttonPanel, BorderLayout.SOUTH); 36 pack(); 37 } 38 39 /** 40 * Adds a radio button that sets the font size of the sample text. 41 * @param name the string to appear on the button 42 * @param size the font size that this button sets 43 */ 44 public void addRadioButton(String name, int size) 45 { 46 boolean selected = size == DEFAULT_SIZE; 47 JRadioButton button = new JRadioButton(name, selected); 48 group.add(button); 49 buttonPanel.add(button); 50 51 // this listener sets the label font size 52 53 ActionListener listener = event -> label.setFont(new Font("Serif", Font.PLAIN, size)); 54 55 button.addActionListener(listener); 56 } 57 }
1 package radioButton; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.34 2015-06-12 8 * @author Cay Horstmann 9 */ 10 public class RadioButtonTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 JFrame frame = new RadioButtonFrame(); 16 frame.setTitle("RadioButtonTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
測試程式5
l 在elipse IDE中除錯執行教材494頁程式12-5,結合執行結果理解程式;
l 掌握邊框的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
1 package border; 2 3 import java.awt.*; 4 import javax.swing.*; 5 import javax.swing.border.*; 6 7 /** 8 * A frame with radio buttons to pick a border style. 9 */ 10 public class BorderFrame extends JFrame 11 { 12 private JPanel demoPanel; 13 private JPanel buttonPanel; 14 private ButtonGroup group; 15 16 public BorderFrame() 17 { 18 demoPanel = new JPanel(); 19 buttonPanel = new JPanel(); 20 group = new ButtonGroup(); 21 22 addRadioButton("Lowered bevel", BorderFactory.createLoweredBevelBorder()); 23 addRadioButton("Raised bevel", BorderFactory.createRaisedBevelBorder()); 24 addRadioButton("Etched", BorderFactory.createEtchedBorder()); 25 addRadioButton("Line", BorderFactory.createLineBorder(Color.BLUE)); 26 addRadioButton("Matte", BorderFactory.createMatteBorder(10, 10, 10, 10, Color.BLUE)); 27 addRadioButton("Empty", BorderFactory.createEmptyBorder()); 28 29 Border etched = BorderFactory.createEtchedBorder(); 30 Border titled = BorderFactory.createTitledBorder(etched, "Border types"); 31 buttonPanel.setBorder(titled); 32 33 setLayout(new GridLayout(2, 1)); 34 add(buttonPanel); 35 add(demoPanel); 36 pack(); 37 } 38 39 public void addRadioButton(String buttonName, Border b) 40 { 41 JRadioButton button = new JRadioButton(buttonName); 42 button.addActionListener(event -> demoPanel.setBorder(b)); 43 group.add(button); 44 buttonPanel.add(button); 45 } 46 }
1 package border; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.34 2015-06-13 8 * @author Cay Horstmann 9 */ 10 public class BorderTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 JFrame frame = new BorderFrame(); 16 frame.setTitle("BorderTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
測試程式6
l 在elipse IDE中除錯執行教材498頁程式12-6,結合執行結果理解程式;
l 掌握組合框元件的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
1 package comboBox; 2 3 import java.awt.BorderLayout; 4 import java.awt.Font; 5 6 import javax.swing.JComboBox; 7 import javax.swing.JFrame; 8 import javax.swing.JLabel; 9 import javax.swing.JPanel; 10 11 /** 12 * A frame with a sample text label and a combo box for selecting font faces. 13 */ 14 public class ComboBoxFrame extends JFrame 15 { 16 private JComboBox<String> faceCombo; 17 private JLabel label; 18 private static final int DEFAULT_SIZE = 24; 19 20 public ComboBoxFrame() 21 { 22 // add the sample text label 23 24 label = new JLabel("The quick brown fox jumps over the lazy dog."); 25 label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE)); 26 add(label, BorderLayout.CENTER); 27 28 // make a combo box and add face names 29 30 faceCombo = new JComboBox<>(); 31 faceCombo.addItem("Serif"); 32 faceCombo.addItem("SansSerif"); 33 faceCombo.addItem("Monospaced"); 34 faceCombo.addItem("Dialog"); 35 faceCombo.addItem("DialogInput"); 36 37 // the combo box listener changes the label font to the selected face name 38 39 faceCombo.addActionListener(event -> 40 label.setFont( 41 new Font(faceCombo.getItemAt(faceCombo.getSelectedIndex()), 42 Font.PLAIN, DEFAULT_SIZE))); 43 44 // add combo box to a panel at the frame's southern border 45 46 JPanel comboPanel = new JPanel(); 47 comboPanel.add(faceCombo); 48 add(comboPanel, BorderLayout.SOUTH); 49 pack(); 50 } 51 }
1 package comboBox; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.35 2015-06-12 8 * @author Cay Horstmann 9 */ 10 public class ComboBoxTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 JFrame frame = new ComboBoxFrame(); 16 frame.setTitle("ComboBoxTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
測試程式7
l 在elipse IDE中除錯執行教材501頁程式12-7,結合執行結果理解程式;
l 掌握滑動條元件的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
1 package slider; 2 3 import java.awt.*; 4 import java.util.*; 5 import javax.swing.*; 6 import javax.swing.event.*; 7 8 /** 9 * A frame with many sliders and a text field to show slider values. 10 */ 11 public class SliderFrame extends JFrame 12 { 13 private JPanel sliderPanel; 14 private JTextField textField; 15 private ChangeListener listener; 16 17 public SliderFrame() 18 { 19 sliderPanel = new JPanel(); 20 sliderPanel.setLayout(new GridBagLayout()); 21 22 // common listener for all sliders 23 listener = event -> { 24 // update text field when the slider value changes 25 JSlider source = (JSlider) event.getSource(); 26 textField.setText("" + source.getValue()); 27 }; 28 29 // add a plain slider 30 31 JSlider slider = new JSlider(); 32 addSlider(slider, "Plain"); 33 34 // add a slider with major and minor ticks 35 36 slider = new JSlider(); 37 slider.setPaintTicks(true); 38 slider.setMajorTickSpacing(20); 39 slider.setMinorTickSpacing(5); 40 addSlider(slider, "Ticks"); 41 42 // add a slider that snaps to ticks 43 44 slider = new JSlider(); 45 slider.setPaintTicks(true); 46 slider.setSnapToTicks(true); 47 slider.setMajorTickSpacing(20); 48 slider.setMinorTickSpacing(5); 49 addSlider(slider, "Snap to ticks"); 50 51 // add a slider with no track 52 53 slider = new JSlider(); 54 slider.setPaintTicks(true); 55 slider.setMajorTickSpacing(20); 56 slider.setMinorTickSpacing(5); 57 slider.setPaintTrack(false); 58 addSlider(slider, "No track"); 59 60 // add an inverted slider 61 62 slider = new JSlider(); 63 slider.setPaintTicks(true); 64 slider.setMajorTickSpacing(20); 65 slider.setMinorTickSpacing(5); 66 slider.setInverted(true); 67 addSlider(slider, "Inverted"); 68 69 // add a slider with numeric labels 70 71 slider = new JSlider(); 72 slider.setPaintTicks(true); 73 slider.setPaintLabels(true); 74 slider.setMajorTickSpacing(20); 75 slider.setMinorTickSpacing(5); 76 addSlider(slider, "Labels"); 77 78 // add a slider with alphabetic labels 79 80 slider = new JSlider(); 81 slider.setPaintLabels(true); 82 slider.setPaintTicks(true); 83 slider.setMajorTickSpacing(20); 84 slider.setMinorTickSpacing(5); 85 86 Dictionary<Integer, Component> labelTable = new Hashtable<>(); 87 labelTable.put(0, new JLabel("A")); 88 labelTable.put(20, new JLabel("B")); 89 labelTable.put(40, new JLabel("C")); 90 labelTable.put(60, new JLabel("D")); 91 labelTable.put(80, new JLabel("E")); 92 labelTable.put(100, new JLabel("F")); 93 94 slider.setLabelTable(labelTable); 95 addSlider(slider, "Custom labels"); 96 97 // add a slider with icon labels 98 99 slider = new JSlider(); 100 slider.setPaintTicks(true); 101 slider.setPaintLabels(true); 102 slider.setSnapToTicks(true); 103 slider.setMajorTickSpacing(20); 104 slider.setMinorTickSpacing(20); 105 106 labelTable = new Hashtable<Integer, Component>(); 107 108 // add card images 109 110 labelTable.put(0, new JLabel(new ImageIcon("nine.gif"))); 111 labelTable.put(20, new JLabel(new ImageIcon("ten.gif"))); 112 labelTable.put(40, new JLabel(new ImageIcon("jack.gif"))); 113 labelTable.put(60, new JLabel(new ImageIcon("queen.gif"))); 114 labelTable.put(80, new JLabel(new ImageIcon("king.gif"))); 115 labelTable.put(100, new JLabel(new ImageIcon("ace.gif"))); 116 117 slider.setLabelTable(labelTable); 118 addSlider(slider, "Icon labels"); 119 120 // add the text field that displays the slider value 121 122 textField = new JTextField(); 123 add(sliderPanel, BorderLayout.CENTER); 124 add(textField, BorderLayout.SOUTH); 125 pack(); 126 } 127 128 /** 129 * Adds a slider to the slider panel and hooks up the listener 130 * @param s the slider 131 * @param description the slider description 132 */ 133 public void addSlider(JSlider s, String description) 134 { 135 s.addChangeListener(listener); 136 JPanel panel = new JPanel(); 137 panel.add(s); 138 panel.add(new JLabel(description)); 139 panel.setAlignmentX(Component.LEFT_ALIGNMENT); 140 GridBagConstraints gbc = new GridBagConstraints(); 141 gbc.gridy = sliderPanel.getComponentCount(); 142 gbc.anchor = GridBagConstraints.WEST; 143 sliderPanel.add(panel, gbc); 144 } 145 }
1 package slider; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.15 2015-06-12 8 * @author Cay Horstmann 9 */ 10 public class SliderTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 SliderFrame frame = new SliderFrame(); 16 frame.setTitle("SliderTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
測試程式8
l 在elipse IDE中除錯執行教材512頁程式12-8,結合執行結果理解程式;
l 掌握選單的建立、選單事件監聽器、複選框和單選按鈕選單項、彈出選單以及快捷鍵和加速器的用法。
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
1 package menu; 2 3 import java.awt.event.*; 4 import javax.swing.*; 5 6 /** 7 * A frame with a sample menu bar. 8 */ 9 public class MenuFrame extends JFrame 10 { 11 private static final int DEFAULT_WIDTH = 300; 12 private static final int DEFAULT_HEIGHT = 200; 13 private Action saveAction; 14 private Action saveAsAction; 15 private JCheckBoxMenuItem readonlyItem; 16 private JPopupMenu popup; 17 18 /** 19 * A sample action that prints the action name to System.out 20 */ 21 class TestAction extends AbstractAction 22 { 23 public TestAction(String name) 24 { 25 super(name); 26 } 27 28 public void actionPerformed(ActionEvent event) 29 { 30 System.out.println(getValue(Action.NAME) + " selected."); 31 } 32 } 33 34 public MenuFrame() 35 { 36 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 37 38 JMenu fileMenu = new JMenu("File"); 39 fileMenu.add(new TestAction("New")); 40 41 // demonstrate accelerators 42 43 JMenuItem openItem = fileMenu.add(new TestAction("Open")); 44 openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O")); 45 46 fileMenu.addSeparator(); 47 48 saveAction = new TestAction("Save"); 49 JMenuItem saveItem = fileMenu.add(saveAction); 50 saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S")); 51 52 saveAsAction = new TestAction("Save As"); 53 fileMenu.add(saveAsAction); 54 fileMenu.addSeparator(); 55 56 fileMenu.add(new AbstractAction("Exit") 57 { 58 public void actionPerformed(ActionEvent event) 59 { 60 System.exit(0); 61 } 62 }); 63 64 // demonstrate checkbox and radio button menus 65 66 readonlyItem = new JCheckBoxMenuItem("Read-only"); 67 readonlyItem.addActionListener(new ActionListener() 68 { 69 public void actionPerformed(ActionEvent event) 70 { 71 boolean saveOk = !readonlyItem.isSelected(); 72 saveAction.setEnabled(saveOk); 73 saveAsAction.setEnabled(saveOk); 74 } 75 }); 76 77 ButtonGroup group = new ButtonGroup(); 78 79 JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert"); 80 insertItem.setSelected(true); 81 JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype"); 82 83 group.add(insertItem); 84 group.add(overtypeItem); 85 86 // demonstrate icons 87 88 Action cutAction = new TestAction("Cut"); 89 cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif")); 90 Action copyAction = new TestAction("Copy"); 91 copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif")); 92 Action pasteAction = new TestAction("Paste"); 93 pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif")); 94 95 JMenu editMenu = new JMenu("Edit"); 96 editMenu.add(cutAction); 97 editMenu.add(copyAction); 98 editMenu.add(pasteAction); 99 100 // demonstrate nested menus 101 102 JMenu optionMenu = new JMenu("Options"); 103 104 optionMenu.add(readonlyItem); 105 optionMenu.addSeparator(); 106 optionMenu.add(insertItem); 107 optionMenu.add(overtypeItem); 108 109 editMenu.addSeparator(); 110 editMenu.add(optionMenu); 111 112 // demonstrate mnemonics 113 114 JMenu helpMenu = new JMenu("Help"); 115 helpMenu.setMnemonic('H'); 116 117 JMenuItem indexItem = new JMenuItem("Index"); 118 indexItem.setMnemonic('I'); 119 helpMenu.add(indexItem); 120 121 // you can also add the mnemonic key to an action 122 Action aboutAction = new TestAction("About"); 123 aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A')); 124 helpMenu.add(aboutAction); 125 126 // add all top-level menus to menu bar 127 128 JMenuBar menuBar = new JMenuBar(); 129 setJMenuBar(menuBar); 130 131 menuBar.add(fileMenu); 132 menuBar.add(editMenu); 133 menuBar.add(helpMenu); 134 135 // demonstrate pop-ups 136 137 popup = new JPopupMenu(); 138 popup.add(cutAction); 139 popup.add(copyAction); 140 popup.add(pasteAction); 141 142 JPanel panel = new JPanel(); 143 panel.setComponentPopupMenu(popup); 144 add(panel); 145 } 146 }
1 package menu; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.24 2012-06-12 8 * @author Cay Horstmann 9 */ 10 public class MenuTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 JFrame frame = new MenuFrame(); 16 frame.setTitle("MenuTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
測試程式9
l 在elipse IDE中除錯執行教材517頁程式12-9,結合執行結果理解程式;
l 掌握工具欄和工具提示的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
1 package toolBar; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 /** 8 * A frame with a toolbar and menu for color changes. 9 */ 10 public class ToolBarFrame extends JFrame 11 { 12 private static final int DEFAULT_WIDTH = 300; 13 private static final int DEFAULT_HEIGHT = 200; 14 private JPanel panel; 15 16 public ToolBarFrame() 17 { 18 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 19 20 // add a panel for color change 21 22 panel = new JPanel(); 23 add(panel, BorderLayout.CENTER); 24 25 // set up actions 26 27 Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE); 28 Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"), 29 Color.YELLOW); 30 Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); 31 32 Action exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif")) 33 { 34 public void actionPerformed(ActionEvent event) 35 { 36 System.exit(0); 37 } 38 }; 39 exitAction.putValue(Acti