1. 程式人生 > >201771010126 王燕《面向物件程式設計(Java)》第十四周學習總結(測試程式11)

201771010126 王燕《面向物件程式設計(Java)》第十四周學習總結(測試程式11)

實驗十四  Swing圖形介面元件

理論部分:

不使用佈局管理器

有時候可能不想使用任何佈局管理器,而只 是想把元件放在一個固定的位置上。下面是將一 個元件定位到某個絕對定位的步驟:

1)將佈局管理器設定為null。

2)將元件新增到容器中。

3)指定想要放置的位置和大小。 frame.setLayout(null); Jbutton ok = new Jbutton("ok"); frame.add(ok); ok.setBounds(10,10,30,15);

定製佈局管理器

 程式設計師可通過自己設計LayoutManager類來實現特殊的佈局方式。定製佈局管理器需要實現LayoutManager介面,並覆蓋以下方法。 void addLayoutComponent(String s,Component c);      

將元件新增到佈局中

引數:s:元件位置的識別符號

   c:被新增的元件

void removeLayoutComponent(Component c);

從本佈局中刪除一個元件

Dimension preferredLayoutSize(Container parent);

返回本佈局下的容器的首選尺寸

Dimension minimumLayoutSize(Container panent);

返回本佈局下的容器的最小尺寸

void layoutContainer(container parent);

擺放容器內的元件

在新增或刪除一個元件時會呼叫前面兩個方法。如果不需要儲存元件的任何附加資訊那麼可以讓著兩個方法什麼都不做。接下來的兩個方法計算元件的最小布局和首選佈局所需要的空間。兩者通常相等,第五個方法真正的實施操作,它呼叫所有元件的Setbounds方法。

遍歷順序

當把很多元件新增到視窗中時,需要考慮遍歷順序問題。視窗被初次使用時,遍歷序列的第一個元件會有鍵盤焦點。沒詞使用者按下TAB鍵,下一個元件就會獲得焦點,

遍歷順序很直觀,順序是從左至右,從上至下,元件按照以下順序進行遍歷:

(1)外觀組合框:

(2)示例文字區:

(3)尺寸組合框:

(4)加粗複選框:

(5)斜體複選框;

如果容器還包括其他的容器,情況會更加複雜。當然點給予另外一個容器時,那個容器左上角的元件就會自動的活動焦點,然後再遍歷那個額容器中的所有元件。最後,將焦點移交給緊跟著那個容器的元件。利用這一點可以將相關元素組織在一起並放置在一個容器中。例如放置在一個面板中。

實驗時間 20178-11-29

1、實驗目的與要求

(1) 掌握GUI佈局管理器用法;

(2) 掌握各類Java Swing元件用途及常用API;

2、實驗內容和步驟

實驗1: 匯入第12章示例程式,測試程式並進行組內討論。

測試程式1

l 在elipse IDE中執行教材479頁程式12-1,結合執行結果理解程式;

l 掌握各種佈局管理器的用法;

l 理解GUI介面中事件處理技術的用途。

l 在佈局管理應用程式碼處添加註釋;

 1 package calculator;
 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 Calculator
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          CalculatorFrame frame = new CalculatorFrame();
16          frame.setTitle("Calculator");
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }
View Code
 1 package calculator;
 2 
 3 import javax.swing.*;
 4 
 5 /**
 6  * A frame with a calculator panel.
 7  */
 8 public class CalculatorFrame extends JFrame
 9 {
10    public CalculatorFrame()
11    {
12       add(new CalculatorPanel());
13       pack();
14    }
15 }
View Code
  1 package calculator;
  2 
  3 import java.awt.*;
  4 import java.awt.event.*;
  5 import javax.swing.*;
  6 
  7 /**
  8  * A panel with calculator buttons and a result display.
  9  */
 10 public class CalculatorPanel extends JPanel
 11 {
 12    private JButton display;
 13    private JPanel panel;
 14    private double result;
 15    private String lastCommand;
 16    private boolean start;
 17 
 18    public CalculatorPanel()
 19    {
 20       setLayout(new BorderLayout());
 21 
 22       result = 0;
 23       lastCommand = "=";
 24       start = true;
 25 
 26       // add the display
 27 
 28       display = new JButton("0");
 29       display.setEnabled(false);
 30       add(display, BorderLayout.NORTH);
 31 
 32       ActionListener insert = new InsertAction();
 33       ActionListener command = new CommandAction();
 34 
 35       // add the buttons in a 4 x 4 grid
 36 
 37       panel = new JPanel();
 38       panel.setLayout(new GridLayout(4, 4));
 39 
 40       addButton("7", insert);
 41       addButton("8", insert);
 42       addButton("9", insert);
 43       addButton("/", command);
 44 
 45       addButton("4", insert);
 46       addButton("5", insert);
 47       addButton("6", insert);
 48       addButton("*", command);
 49 
 50       addButton("1", insert);
 51       addButton("2", insert);
 52       addButton("3", insert);
 53       addButton("-", command);
 54 
 55       addButton("0", insert);
 56       addButton(".", insert);
 57       addButton("=", command);
 58       addButton("+", command);
 59 
 60       add(panel, BorderLayout.CENTER);
 61    }
 62 
 63    /**
 64     * Adds a button to the center panel.
 65     * @param label the button label
 66     * @param listener the button listener
 67     */
 68    private void addButton(String label, ActionListener listener)
 69    {
 70       JButton button = new JButton(label);
 71       button.addActionListener(listener);
 72       panel.add(button);
 73    }
 74 
 75    /**
 76     * This action inserts the button action string to the end of the display text.
 77     */
 78    private class InsertAction implements ActionListener
 79    {
 80       public void actionPerformed(ActionEvent event)
 81       {
 82          String input = event.getActionCommand();
 83          if (start)
 84          {
 85             display.setText("");
 86             start = false;
 87          }
 88          display.setText(display.getText() + input);
 89       }
 90    }
 91 
 92    /**
 93     * This action executes the command that the button action string denotes.
 94     */
 95    private class CommandAction implements ActionListener
 96    {
 97       public void actionPerformed(ActionEvent event)
 98       {
 99          String command = event.getActionCommand();
100 
101          if (start)
102          {
103             if (command.equals("-"))
104             {
105                display.setText(command);
106                start = false;
107             }
108             else lastCommand = command;
109          }
110          else
111          {
112             calculate(Double.parseDouble(display.getText()));
113             lastCommand = command;
114             start = true;
115          }
116       }
117    }
118 
119    /**
120     * Carries out the pending calculation.
121     * @param x the value to be accumulated with the prior result.
122     */
123    public void calculate(double x)
124    {
125       if (lastCommand.equals("+")) result += x;
126       else if (lastCommand.equals("-")) result -= x;
127       else if (lastCommand.equals("*")) result *= x;
128       else if (lastCommand.equals("/")) result /= x;
129       else if (lastCommand.equals("=")) result = x;
130       display.setText("" + result);
131    }
132 }
View Code

 測試程式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 }
View Code
 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 }
View Code

 測試程式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("The quick brown fox jumps over the lazy dog.");
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 }
View Code
 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 }
View Code

 

 測試程式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 }
View Code
 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 }
View Code

 

測試程式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 }
View Code
 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 }
View Code

 

測試程式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 }
View Code
 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 }
View Code

 

 測試程式7

l 在elipse IDE中除錯執行教材501頁程式12-7,結合執行結果理解程式;

 掌握滑動條元件的用法;

l 記錄示例程式碼閱讀理解中存在的問題與疑惑。

 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 }
View Code
  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 }
View Code

 

 測試程式8

l 在elipse IDE中除錯執行教材512頁程式12-8,結合執行結果理解程式;

l 掌握選單的建立、選單事件監聽器、複選框和單選按鈕選單項、彈出選單以及快捷鍵和加速器的用法。

l 記錄示例程式碼閱讀理解中存在的問題與疑惑。

 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 }
View Code
  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       Act