201771010128王玉蘭《面向物件程式設計(Java)第十四周學習總結》
第一部分:理論知識總結:
(1)Swing
設計模式(Design pattern)是設計者一種流行的 思考設計問題的方法,是一套被反覆使用,多數人 知曉的,經過分類編目的,程式碼設計經驗的總結。
使用設計模式是為了可重用程式碼、讓程式碼更容易被 他人理解、保證程式碼可靠性。
每一個模式描述了一個不斷重複發生的設計問題, 以及該問題的核心解決方案
模型-檢視-控制器設計模式(Model –ViewController )是Java EE平臺下建立Web 應用程式 的重要設計模式
(2)MVC設計模式
MVC設計模式 –Model(模型):是程式中用於處理程式資料邏 輯的部分,通常模型負責在資料庫中存取資料。
–View(檢視):是程式中處理資料顯示的部分, 通常檢視依據模型存取的資料建立。
–Controller(控制器):是程式中處理使用者互動 的部分。通常控制器負責從檢視讀取資料,控制 使用者輸入,並向模型傳送資料。
(3)佈局管理器
A:為了設計美觀合理的GUI介面,需要考慮元件在 容器元件中的位置和相互關係,就需要學習佈局 設計的知識。
B:在java的GUI應用程式介面設計中,佈局控制通 過為容器設定佈局管理器來實現的。
C:佈局管理器是一組類。 –實現java.awt.LayoutManager介面 –決定容器中元件的位置和大小 Java.awt包中定義了5種佈局管理類,每一種布 局管理類對應一種佈局策略。
D:每個容器都有與之相關的預設佈局管理器。
E:當一個容器選定一種佈局策略時,它應該建立該 策略對應的佈局管理器物件,並將此物件設定為 自己的佈局管理器。
5種佈局管理器:
1)FlowLayout:流佈局(Applet和Panel的預設 佈局管理器)
2)BorderLayout:邊框佈局(Window、Frame和 Dialog的預設佈局管理器)
3)GridLayout:網格佈局
4)GridBagLayout:網格組佈局
5)CardLayout:卡片佈局
(4)文字輸入
文字域(JTextField): 用於獲取單行文字輸入。
文字域的使用方法: JPanelpanel = new JPanel();
JTextFieldtextField= new JTextField("Default input", 20);
panel.add(textField); –第一個引數“Default input”:
將文字域的預設 顯示值為Default input –第二個引數20:表示文字域顯示寬度為20列。
–若要重新設定列數,可使用setColumns方法。
(5)選擇元件
標籤是容納文字的元件。它們沒有任何修飾(如沒有邊界 ),也不響應使用者輸入。
1.bold = new JCheckBox("Bold"); 複選框自動地帶有表示標籤。
2. JCheckBox(String label,Icon icon); 構造帶有標籤與圖示的複選框,預設初始未被選擇。
3.JCheckBox(String label,boolean state); 用指定的標籤和初始化選擇狀態構造一個複選框
(6)選單
首先建立一個選單欄 選單欄是一個可以新增到容器元件任何位置 的元件。通常放置在框架的頂部。 JMenuBarmenuBar=new JMenuBar();
呼叫框架的setJMenuBar方法可將一個選單欄對 象新增到框架上 frame.setJMenuBar(menuBar);
建立選單物件,並將選單物件新增到選單欄中 JMenueditMenu=new Jmenu("Edit"); menuBar.add(editMenu);
向選單物件新增一個選單項。向選單物件新增一個選單項。 JMenItempasteItem=new JMenItem(); editMenu.add(pasteItem);
向選單物件新增分隔符行。 editMenu.addSeperator(); 向選單物件項新增子選單。 JMenuoptionsMenu=new Jmenu(“option”); editMenu.add(optionsMenu);
第二部分:實驗
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 javax.swing.*; /** * @version 1.34 2015-06-12 * @author Cay Horstmann */ 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.*; /** * A frame with a calculator panel. */ public class CalculatorFrame extends JFrame { public CalculatorFrame() { add(new CalculatorPanel()); pack(); } }
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);//新增display元件,並將其放置北面 //生成了2個監聽器物件 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));//定義了網格佈局管理器 //生成了16個事件源 addButton("0", insert); addButton("1", insert); addButton("2", insert); addButton("/", command); addButton("3", insert); addButton("4", insert); addButton("5", insert); addButton("*", command); addButton("6", insert); addButton("7", insert); addButton("8", insert); addButton("-", command); addButton("9", insert); addButton(".", insert); addButton("=", command); addButton("+", command); add(panel, BorderLayout.CENTER); JButton b1=new JButton("驗證"); add(b1,BorderLayout.SOUTH); JButton b2=new JButton("驗證1"); add(b2,BorderLayout.WEST); JButton b3=new JButton("驗證2"); add(b3,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);//將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 {//將數字字串呼叫parse方法轉換為數字 calculate(Double.parseDouble(display.getText())); 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);//進行字串的轉換 } }
執行結果:
測試程式2
l 在elipse IDE中除錯執行教材486頁程式12-2,結合執行結果理解程式;
l 掌握各種文字元件的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
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; /** * A frame with sample text components. */ 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
l 在elipse IDE中除錯執行教材489頁程式12-3,結合執行結果理解程式;
l 掌握複選框元件的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
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.*; /** * A frame with a sample text label and check boxes for selecting font * 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
l 在elipse IDE中除錯執行教材491頁程式12-4,執行結果理解程式;
l 掌握單選按鈕元件的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
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.*; /** * A frame with a sample text label and radio buttons for selecting font sizes. */ 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); // add the radio buttons buttonPanel = new JPanel(); group = new ButtonGroup(); addRadioButton("Small", 8); addRadioButton("Medium", 12); addRadioButton("Large", 18); addRadioButton("Extra large", 36); add(buttonPanel, BorderLayout.SOUTH); pack(); } /** * Adds a radio button that sets the font size of the sample text. * @param name the string to appear on the button * @param size the font size that this button sets */ 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
l 在elipse IDE中除錯執行教材494頁程式12-5,結合執行結果理解程式;
l 掌握邊框的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
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.*; /** * A frame with radio buttons to pick a border style. */ 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
l 在elipse IDE中除錯執行教材498頁程式12-6,結合執行結果理解程式;
l 掌握組合框元件的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
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; /** * A frame with a sample text label and a combo box for selecting font faces. */ 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
l 在elipse IDE中除錯執行教材501頁程式12-7,結合執行結果理解程式;
l 掌握滑動條元件的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
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.*; /** * A frame with many sliders and a text field to show slider values. */ 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 -> { // update text field when the slider value changes 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(); } /** * Adds a slider to the slider panel and hooks up the listener * @param s the slider * @param description the slider description */ 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
l 在elipse IDE中除錯執行教材512頁程式12-8,結合執行結果理解程式;
l 掌握選單的建立、選單事件監聽器、複選框和單選按鈕選單項、彈出選單以及快捷鍵和加速器的用法。
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
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.*; /** * 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; /** * A sample action that prints the action name to System.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
l 在elipse IDE中除錯執行教材517頁程式12-9,結合執行結果理解程式;
l 掌握工具欄和工具提示的用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
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.*; /** * 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); // set up actions 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"); // populate toolbar JToolBar bar = new JToolBar(); bar.add(blueAction); bar.add(yellowAction); bar.add(redAction); bar.addSeparator(); bar.add(exitAction); add(bar, BorderLayout.NORTH); // populate menu 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); } /** * 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); } } }
執行結果:
測試程式10
l 在elipse IDE中除錯執行教材524頁程式12-10、12-11,結合執行結果理解程式,瞭解GridbagLayout的用法。
l 在elipse IDE中除錯執行教材533頁程式12-12,結合程式執行結果理解程式,瞭解GroupLayout的用法。
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
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 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.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); }); } }
執行結果:
測試程式11
l 在elipse IDE中除錯執行教材539頁程式12-13、12-14,結合執行結果理解程式;
l 掌握定製佈局管理器的用法。
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
package circleLayout; import java.awt.*; /** * A layout manager that lays out components along a circle. */ public class CircleLayout implements LayoutManager { private int minWidth = 0; private int minHeight = 0; private int preferredWidth = 0; private int preferredHeight = 0; private boolean sizesSet = false; private int maxComponentWidth = 0; private int maxComponentHeight = 0; //如果佈局管理器使用每元件字串,則將元件 comp 新增到佈局,並將它與 name 指定的字串關聯 public void addLayoutComponent(String name, Component comp) { } //從佈局移除指定元件。 public void removeLayoutComponent(Component comp) { } public void setSizes(Container parent) { if (sizesSet) return; int n = parent.getComponentCount(); preferredWidth = 0; preferredHeight = 0; minWidth = 0; minHeight = 0; maxComponentWidth = 0; maxComponentHeight = 0; // 計算最大部件寬度和高度 // 並將優選尺寸設定為部件尺寸的總和。 for (int i = 0; i < n; i++) { Component c = parent.getComponent(i); if (c.isVisible()) { Dimension d = c.getPreferredSize(); maxComponentWidth = Math.max(maxComponentWidth, d.width); maxComponentHeight = Math.max(maxComponentHeight, d.height); preferredWidth += d.width; preferredHeight += d.height; } } minWidth = preferredWidth / 2; minHeight = preferredHeight / 2; sizesSet = true; } public Dimension preferredLayoutSize(Container parent) { setSizes(parent); Insets insets = parent.getInsets(); int width = preferredWidth + insets.left + insets.right; int height = preferredHeight + insets.top + insets.bottom; return new Dimension(width, height); } //給定指定容器所包含的元件,計算該容器的最小大小維數。 public Dimension minimumLayoutSize(Container parent) { setSizes(parent); Insets insets = parent.getInsets(); int width = minWidth + insets.left + insets.right; int height = minHeight + insets.top + insets.bottom; return new Dimension(width, height);//引數的指定 } //佈置指定容器 public void layoutContainer(Container parent) { setSizes(parent); // 圓的計算中心 Insets insets = parent.getInsets(); int containerWidth = parent.getSize().width - insets.left - insets.right; int containerHeight = parent.getSize().height - insets.top - insets.bottom; int xcenter = insets.left + containerWidth / 2; int ycenter = insets.top + containerHeight / 2; //計算圓的半徑 int xradius = (containerWidth - maxComponentWidth) / 2; int yradius = (containerHeight - maxComponentHeight) / 2; int radius = Math.min(xradius, yradius); // 沿著圓圈佈置元件 int n = parent.getComponentCount(); for (int i = 0; i < n; i++) { Component c = parent.getComponent(i); if (c.isVisible()) { double angle = 2 * Math.PI * i / n; // 分量中心點 int x = xcenter + (int) (Math.cos(angle) * radius); int y = ycenter + (int) (Math.sin(angle) * radius); // 移動元件,使其中心為( x ^ y ) // 並且它的尺寸是它的優選尺寸 Dimension d = c.getPreferredSize(); c.setBounds(x - d.width / 2, y - d.height / 2, d.width, d.height); } } } }
package circleLayout; import javax.swing.*; /** * A frame that shows buttons arranged along a circle. */ public class CircleLayoutFrame extends JFrame { public CircleLayoutFrame() { setLayout(new CircleLayout()); add(new JButton("Yellow")); add(new JButton("Blue")); add(new JButton("Red")); add(new JButton("Green")); add(new JButton("Orange")); add(new JButton("Fuchsia")); add(new JButton("Indigo")); pack(); } }
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); }); } }
執行結果:
測試程式12
l 在elipse IDE中除錯執行教材544頁程式12-15、12-16,結合執行結果理解程式;
l 掌握選項對話方塊的用法。
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
package optionDialog; import javax.swing.*; /** * A panel with radio buttons inside a titled border. */ public class ButtonPanel extends JPanel { private ButtonGroup group; /** * Constructs a button panel. * @param title the title shown in the border * @param options an array of radio button labels */ public ButtonPanel(String title, String... options) { setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title)); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); group = new ButtonGroup(); //為每個選項做一個單選按鈕 for (String option : options) { JRadioButton b = new JRadioButton(option); b.setActionCommand(option); add(b); group.add(b); b.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(); } }
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() { JPanel 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); // 新增帶有顯示按鈕的面板 JPanel showPanel = new JPanel(); JButton showButton = new JButton("Show"); showButton.addActionListener(new ShowAction()); showPanel.add(showButton); add(gridPanel, BorderLayout.CENTER); add(showPanel, BorderLayout.SOUTH); pack(); } /** * Gets the currently selected message. * @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); } 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) { Graphics2D g2 = (Graphics2D) g; Rectangle2D 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); } }
package optionDialog; import java.awt.*; import javax.swing.*; /** * @version 1.34 2015-06-12 * @author Cay Horstmann */ public class OptionDialogTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new OptionDialogFrame(); frame.setTitle("OptionDialogTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
測試程式13
l 在elipse IDE中除錯執行教材552頁程式12-17、12-18,結合執行結果理解程式;
l 掌握對話方塊的建立方法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
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); // 新增HTML標籤到中心 add( new JLabel( "<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"), BorderLayout.CENTER); // OK按鈕關閉對話方塊 JButton ok = new JButton("OK"); ok.addActionListener(event -> setVisible(false)); // 新增OK按鈕到南部邊框 JPanel panel = new JPanel(); panel.add(ok); add(panel, BorderLayout.SOUTH); pack(); } }
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); // 構造一個檔案選單。 JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); // 新增和退出選單項 //有關專案顯示有關對話方塊. JMenuItem aboutItem = new JMenuItem("About"); aboutItem.addActionListener(event -> { if (dialog == null) // first time dialog = new AboutDialog(DialogFrame.this); dialog.setVisible(true); // pop up dialog }); fileMenu.add(aboutItem); // 退出項退出程式。 JMenuItem exitItem = new JMenuItem("Exit"); exitItem.addActionListener(event -> System.exit(0)); fileMenu.add(exitItem); } }
package dialog; import java.awt.*; import javax.swing.*; /** * @version 1.34 2012-06-12 * @author Cay Horstmann */ public class DialogTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new DialogFrame(); frame.setTitle("DialogTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
測試程式14
l 在elipse IDE中除錯執行教材556頁程式12-19、12-20,結合執行結果理解程式;
l 掌握對話方塊的資料交換用法;
l 記錄示例程式碼閱讀理解中存在的問題與疑惑。
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() { // 建構檔案選單 JMenuBar mbar = new JMenuBar(); setJMenuBar(mbar); JMenu fileMenu = new JMenu("File"); mbar.add(fileMenu); //新增連線和退出選單項 JMenuItem connectItem = new JMenuItem("Connect"); connectItem.addActionListener(new ConnectAction()); fileMenu.add(connectItem); // 退出項退出程式 JMenuItem exitItem = new JMenuItem("Exit"); exitItem.addActionListener(event -> System.exit(0)); fileMenu.add(exitItem); textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS); add(new JScrollPane(textArea), BorderLayout.CENTER); pack(); } /** * The Connect action pops up the password dialog. */ private class ConnectAction implements ActionListener { public void actionPerformed(ActionEvent event) { // 如果第一次,構造對話方塊 if (dialog == null) dialog = new PasswordChooser(); //設定預設值 dialog.setUser(new User("yourname", null)); //彈出對話方塊 if (dialog.showDialog(DataExchangeFrame.this, "Connect")) { // 如果接受,則檢索使用者輸入 User u = dialog.getUser(); textArea.append("user name = " + u.getName() + ", password = " + (new String(u.getPassword())) + "\n"); } } } }
package dataExchange; import java.awt.*; import javax.swing.*; /** * @version 1.34 2015-06-12 * @author Cay Horstmann */ public class DataExchangeTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new DataExchangeFrame(); frame.setTitle("DataExchangeTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
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()); // 構造帶有使用者名稱和密碼欄位的面板 JPanel 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); //建立“確定”並取消終止對話方塊的按鈕 okButton = new JButton("Ok"); okButton.addActionListener(event -> { ok = true; dialog.setVisible(false); }); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(event -> dialog.setVisible(false)); // 新增按鈕到南部邊界 JPanel buttonPanel = new JPanel(); buttonPanel.add(okButton); buttonPanel.add(cancelBu