1. 程式人生 > >張雲飛 201771010143 《面對物件程式設計(java)》第十四周學習總結 第十三組

張雲飛 201771010143 《面對物件程式設計(java)》第十四周學習總結 第十三組

1、實驗目的與要求

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

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

2、實驗內容和步驟

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

測試程式1

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

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

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

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

程式碼:

package calculator;

import javax.swing.*;

/**
* A frame with a calculator panel.
*/
public class CalculatorFrame extends JFrame
{
public CalculatorFrame()
{
add(new CalculatorPanel());
pack();
}
}

CalculatorFrame


複製程式碼
 
  
   複製程式碼
   
  
 
 
 

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);
});
}
}

Calculator


複製程式碼
 
  
   複製程式碼
   
  
 
 
 

package calculator;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
* 具有計算器按鈕和結果顯示的面板
*/
public class CalculatorPanel extends JPanel {
private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;

public CalculatorPanel() {
setLayout(new BorderLayout());

result = 0;
lastCommand = "=";
start = true;

// 新增display

display = new JButton("0");
display.setEnabled(false);
add(display, BorderLayout.NORTH);

ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();

// 在4×4網格中新增按鈕

panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));

addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);

addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);

addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);

addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);

add(panel, BorderLayout.CENTER);// 把面板新增在邊框佈局的中央
}

/**
* 向中心面板新增一個按鈕
*
* @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);
}

/**
* 此操作將按鈕操作字串插入到顯示文字的末尾
*/
private class InsertAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();// 標識此事件命令的字串
if (start) {
display.setText("");
start = false;
}
display.setText(display.getText() + input);
}
}

/**
* 此操作執行按鈕操作字串所表示的命令
*/
private class CommandAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();

if (start) {
if (command.equals("-"))// 負數的情況
{
display.setText(command);
start = false;
} else
lastCommand = command;
} else {
calculate(Double.parseDouble(display.getText()));// 把display中的string轉換為double
lastCommand = command;
start = true;
}
}
}

/**
* 執行即將發生的計算
*
* @param x值與先前結果一起累積。
*/
public void calculate(double x) {
if (lastCommand.equals("+"))
result += x;
else if (lastCommand.equals("-"))
result -= x;
else if (lastCommand.equals("*"))
result *= x;
else if (lastCommand.equals("/"))
result /= x;
else if (lastCommand.equals("="))
result = x;
display.setText("" + result);// 在double前新增""可轉換為string
}
}

CalculatorPanel


複製程式碼
 
  
   複製程式碼
   
  
 

結果:

測試程式2

elipse IDE中除錯執行教材486頁程式12-2,結合執行結果理解程式;

掌握各種文字元件的用法;

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

 

package Forth;

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();


//定義一個Panel,設定了表格佈局管理器並指定行與列

JPanel northPanel = new JPanel();
northPanel.setLayout(new GridLayout(2, 2));
// 新增文字域的標籤

northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT));
northPanel.add(textField);//將文字域新增到panel
northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT));
northPanel.add(passwordField);

add(northPanel, BorderLayout.NORTH);//將pannel新增到frame


JTextArea textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS);
JScrollPane scrollPane = new JScrollPane(textArea);

add(scrollPane, BorderLayout.CENTER);

// 新增按鈕以將文字附加到文字區域

JPanel southPanel = new JPanel();

//定義一個按鈕,新增到frame下方,並定義監聽事件,點選按鈕,文字區顯示使用者名稱與密碼
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();
}
}

TextComponentFrame

複製程式碼
 
  
   複製程式碼
   
  
 

 

測試程式3

elipse IDE中除錯執行教材489頁程式12-3,結合執行結果理解程式;

掌握複選框元件的用法;

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

package practise;

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);
});
}
}

CheckBoxTest

 

package practise;

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()
{
// add the sample text label
//新增示例文字標籤;

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();
}
}

CheckBoxFrame

測試程式4

elipse IDE中除錯執行教材491頁程式12-4,執行結果理解程式;

掌握單選按鈕元件的用法;

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

package Second;

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);
});
}
}

RadioButtonTest

package Second;

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);

// 新增單選按鈕;

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);
}
}

RadioButtonFrame

測試程式5

elipse IDE中除錯執行教材494頁程式12-5,結合執行結果理解程式;

掌握邊框的用法;

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

package Third;

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);
});
}
}

BorderTest

package Third;

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());//建立一個具有3D效果的直線邊框;
addRadioButton("Line", BorderFactory.createLineBorder(Color.BLUE));//建立一個具有3D效果的藍色直線邊框;
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);
}
}

BorderFrame

測試程式6

elipse IDE中除錯執行教材498頁程式12-6,結合執行結果理解程式;

掌握組合框元件的用法;

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

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)
{
//lambda表示式
EventQueue.invokeLater(() -> {
//構造frame框架物件
JFrame frame = new ComboBoxFrame();
//設定標題
frame.setTitle("ComboBoxTest");
//設定使用者在此窗體上發起 "close" 時預設執行的操作。
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//設定框架是否可見
frame.setVisible(true);
});
}
}

ComboBoxTest

 

 

 

測試程式7

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

掌握滑動條元件的用法;

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

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;

/**
* 具有示例文字標籤和用於選擇字型外觀的組合框的框架。
* 組合框:將按鈕或可編輯欄位與下拉列表組合的元件。
* 使用者可以從下拉列表中選擇值,下拉列表在使用者請求時顯示。
* 如果使組合框處於可編輯狀態,則組合框將包括使用者可在其中鍵入值的可編輯欄位。
*/

//ComboBoxFrame繼承於JFrame類
public class ComboBoxFrame extends JFrame
{
//設定ComboBoxFrame的私有屬性
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");

// 組合框監聽器將標籤字型更改為所選的名稱(新增監聽器,使用lambda表示式)

faceCombo.addActionListener(event ->
//設定標籤的字型
label.setFont(
//getItemAt用於返回指定索引處的列表項;getSelectedIndex用於返回當前選擇的選項
new Font(faceCombo.getItemAt(faceCombo.getSelectedIndex()),
Font.PLAIN, DEFAULT_SIZE)));

// 將組合框新增到框架南部邊界的面板

JPanel comboPanel = new JPanel();
comboPanel.add(faceCombo);
add(comboPanel, BorderLayout.SOUTH);
pack();
}
}

ComboBoxFrame

複製程式碼
 
 
  複製程式碼
  
 

 

 

測試程式8

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

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

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

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"));

// demonstrate accelerators

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);
}
});

// demonstrate checkbox and radio button menus

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);

// demonstrate icons

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);

// demonstrate nested menus

JMenu optionMenu = new JMenu("Options");

optionMenu.add(readonlyItem);
optionMenu.addSeparator();
optionMenu.add(insertItem);
optionMenu.add(overtypeItem);

editMenu.addSeparator();
editMenu.add(optionMenu);

// demonstrate mnemonics

JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');

JMenuItem indexItem = new JMenuItem("Index");
indexItem.setMnemonic('I');
helpMenu.add(indexItem);

// you can also add the mnemonic key to an action
Action aboutAction = new TestAction("About");
aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));
helpMenu.add(aboutAction);

// add all top-level menus to menu bar

JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);

menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);

// demonstrate pop-ups

popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction);

JPanel panel = new JPanel();
panel.setComponentPopupMenu(popup);
add(panel);
}
}

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);
});
}
}

 

 

測試程式9

elipse IDE中除錯執行教材517頁程式12-9,結合執行結果理解程式;

掌握工具欄和工具提示的用法;

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

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();//建立新的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);//用Action物件填充工具欄
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

elipse IDE中除錯執行教材524頁程式12-1012-11,結合執行結果理解程式,瞭解GridbagLayout的用法。

elipse IDE中除錯執行教材533頁程式12-12,結合程式執行結果理解程式,瞭解GroupLayout的用法。

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

 

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();
}
}

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;
}
}

 

 

 

測試程式11

elipse IDE中除錯執行教材539頁程式12-1312-14,結合執行結果理解程式;

掌握定製佈局管理器的用法。

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

       

 

 

測試程式12

elipse IDE中除錯執行教材544頁程式12-1512-16,結合執行結果理解程式;

掌握選項對話方塊的用法。

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

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);

// add a panel with a Show button

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

elipse IDE中除錯執行教材552頁程式12-1712-18,結合執行結果理解程式;

掌握對話方塊的建立方法;

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

package 課本示例13;

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);
});
}
}

 

package 課本示例13;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;

/**
* 包含用於選擇各種選項對話方塊的設定的框架。
*/
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);

// add a panel with a Show button

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;
}

/**
* 獲取所選訊息或選項型別
* @param面板訊息型別或確認面板
* @return JOptionPane類中選定的XXX_MESSAGE或XXX_OPTION常量
*/
public int getType(ButtonPanel panel)
{
String s = panel.getSelection();
try
{
return JOptionPane.class.getField(s).getInt(null);
}
catch (Exception e)
{
return -1;
}
}

/**
* “顯示”按鈕的動作偵聽器顯示“確認”,“輸入”,“訊息”或“選項”對話方塊
*取決於“型別”面板選擇。
*/
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]);
}
}
}

/**
* 具有塗漆表面的元件
*/

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 課本示例13;

 

import javax.swing.*;

 

/**

 * 帶標題邊框內的單選按鈕的面板.

 */

public class ButtonPanel extends JPanel

{

   private ButtonGroup group;

 

   /**

    * 構造一個按鈕面板.

    * @param標題邊框中顯示的標題

    * @param選項一組單選按鈕標籤

    */

   public ButtonPanel(String title, String... options)

   {

      setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));

      setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

      group = new ButtonGroup();

 

      // make one radio button for each option

      for (String option : options)

      {

         JRadioButton b = new JRadioButton(option);

         b.setActionCommand(option);

         add(b);

         group.add(b);

         b.setSelected(option == options[0]);

      }

   }

 

   /**

    * 獲取當前選定的選項。

    * @return當前所選單選按鈕的標籤

    */

   public String getSelection()

   {

      return group.getSelection().getActionCommand();

   }

}

 

 

 

 

測試程式14

elipse IDE中除錯執行教材556頁程式12-1912-20,結合執行結果理解程式;

掌握對話方塊的資料交換用法;

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

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()
{
// construct a File menu

JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File");
mbar.add(fileMenu);

// add Connect and Exit menu items

JMenuItem connectItem = new JMenuItem("Connect");
connectItem.addActionListener(new ConnectAction());
fileMenu.add(connectItem);

// The Exit item exits the program

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 first time, construct dialog

if (dialog == null) dialog = new PasswordChooser();

// set default values
dialog.setUser(new User("yourname", null));

// pop up dialog
if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
{
// if accepted, retrieve user input
User u = dialog.getUser();
textArea.append("user name = " + u.getName() + ", password = "
+ (new String(u.getPassword())) + "\n");
}
}
}
}

 

 

測試程式15

elipse IDE中除錯執行教材556頁程式12-21、12-2212-23,結合程式執行結果理解程式;

掌握檔案對話方塊的用法;

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

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()
{
// construct a File menu

JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File");
mbar.add(fileMenu);

// add Connect and Exit menu items

JMenuItem connectItem = new JMenuItem("Connect");
connectItem.addActionListener(new ConnectAction());
fileMenu.add(connectItem);

// The Exit item exits the program

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 first time, construct dialog

if (dialog == null) dialog = new PasswordChooser();

// set default values
dialog.setUser(new User("yourname", null));

// pop up dialog
if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
{
// if accepted, retrieve user input
User u = dialog.getUser();
textArea.append("user name = " + u.getName() + ", password = "
+ (new String(u.getPassword())) + "\n");
}
}
}
}

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());

// construct a panel with user name and password fields

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);

// create Ok and Cancel buttons that terminate the dialog

okButton = new JButton("Ok");
okButton.addActionListener(event -> {
ok = true;
dialog.setVisible(false);
});

JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(event -> dialog.setVisible(false));

// add buttons to southern border

JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
add(buttonPanel, BorderLayout.SOUTH);
}

/**
* Sets the dialog defaults.
* @param u the default user information
*/
public void setUser(User u)
{
username.setText(u.getName());
}

/**
* Gets the dialog entries.
* @return a User object whose state represents the dialog entries
*/
public User getUser()
{
return new User(username.getText(), password.getPassword());
}

/**
* Show the chooser panel in a dialog
* @param parent a component in the owner frame or null
* @param title the dialog window title
*/
public boolean showDialog(Component parent, String title)
{
ok = false;

// locate the owner frame

Frame owner = null;
if (parent instanceof Frame)
owner = (Frame) parent;
else
owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);

// if first time, or if owner has changed, make new dialog

if (dialog == null || dialog.getOwner() != owner)
{
dialog = new JDialog(owner, true);
dialog.add(this);
dialog.getRootPane().setDefaultButton(okButton);
dialog.pack();
}

// set title and show dialog

dialog.setTitle(title);
dialog.setVisible(true);
return ok;
}
}

package dataExchange;

/**
* A user has a name and password. For security reasons, t