1. 程式人生 > >201771010135 楊蓉慶/張燕/楊玲《面對物件程式設計(java)》第十四周學習總結

201771010135 楊蓉慶/張燕/楊玲《面對物件程式設計(java)》第十四周學習總結

1 、實驗目的與要求

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

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

一、理論知識

 Swing和MVC設計模式

(1)設計模式(Design pattern)是設計者一種流行的 思考設計問題的方法,是一套被反覆使用,多數人 知曉的,經過分類編目的,程式碼設計經驗的總結。

(2)模型-檢視-控制器設計模式(Model –ViewController )是Java EE平臺下建立 Web 應用程式 的重要設計模式。

(3)MVC設計模式 – Model(模型):是程式中用於處理程式資料邏 輯的部分,通常模型負責在資料庫中存取資料。

– View(檢視):是程式中處理資料顯示的部分, 通常檢視依據模型存取的資料建立。

– Controller(控制器):是程式中處理使用者互動 的部分。通常控制器負責從檢視讀取資料,控制 使用者輸入,並向模型傳送資料。

(4)Java元件有內容、外觀、行為三個主要元素;

 佈局管理器

(1)佈局管理器是一組類。 – 實現 java.awt.LayoutManager 介面 – 決定容器中元件的位置和大小

Java.awt包中定義了5種佈局管理類,每一種布 局管理類對應一種佈局策略。

每個容器都有與之相關的預設佈局管理器。

(2)5種佈局管理器:(1)FlowLayout: 流佈局(Applet和Panel的預設 佈局管理器) (2)BorderLayout:邊框佈局( Window、Frame和 Dialog的預設佈局管理器) (3)GridLayout: 網格佈局 (4)GridBagLayout: 網格組佈局 (5)CardLayout :卡片佈局

3、GridLayout的建構函式如下:1、GridLayout():生成一個單行單列的網格佈局

2、GridLayout(int rows,int cols):生成一個設定行數 和列數的網格佈局

3、GridLayout(int rows,int columns,int hgap,int vgap): 可以設定元件之間的水平和垂直間隔

 文字輸入

(1)文字域(JTextField) : 用於獲取單行文字輸入。

(2)文字區(JTextArea)元件可讓使用者輸入多行文 本。生成JTextArea元件物件時,可以指定文字 區的行數和列數: textArea = new JTextArea(8, 40);

  (3)文字區與文字域的異同相同之處: 文字域和文字區元件都可用於獲取文字輸入。

不同之處:  文字域只能接受單行文字的輸入;  文字區能夠接受多行文字的輸入。

(4)文字區JTextArea的常用API:Java.swing. JTextArea 1.2 – JTextArea(int rows, int cols)

構造一個rows行cols列的文字區物件 – JTextArea(String text,int rows, int cols)

用初始文字構造一個文字區物件 – void setRows(int rows)

設定文字域使用的行數 – void append(String newText)

將給定文字附加到文字區中已有文字的後面 – void setLineWrap(boolean wrap)

開啟或關閉換行

(5)標籤元件:標籤是容納文字的元件。它們沒有任何修飾(如沒有邊界 ),也不響應使用者輸入。

 標籤的常用用途之一就是標識元件,例如標識文字域。其使用步驟如下:

1. 建立一個JLabel元件

2. 將標籤元件放置在距離被標識元件足夠近的地方。

(6)密碼域:密碼域是一種特殊型別的文字域。每個輸入的字 符都用回顯字元實現,典型的回顯字元為*。

– JPassWordField(String text, int columns) 構造一個密碼域物件

(7)滾動窗格:

Swing中文字區沒有滾動條,若需要滾動條。將文 本區放入一個滾動窗格中即可。

常用API—Java.swing. JScrollPane(教材340頁) – JScrollPane(Component c) 在元件c上新增滾動條,返回新增後的元件。

 選擇元件

複選框  單選按鈕  邊框  組合框  滑動條

(1)複選框構造器 1.bold = new JCheckBox("Bold"); 複選框自動地帶有表示標籤。

2. JCheckBox(String label,Icon icon); 構造帶有標籤與圖示的複選框,預設初始未被選擇。

3.JCheckBox(String label,boolean state); 用指定的標籤和初始化選擇狀態構造一個複選框

(2)單選按鈕的構造器(教材492頁) 1.JRadioButton(String label,Icon icon); 建立一個帶標籤和圖示的單選按鈕

2.JRadioButton(String label,boolean state); 用指定的標籤和初始化狀態構造單選按鈕

(3)按鈕組:為單選按鈕組構造一個ButtonGroup的物件。 然後,再將JRadioButton型別的物件新增到按鈕 組中。按鈕組負責在新按鈕被按下的時,取消前一 個按鈕的選擇狀態。

(4)如果在一個視窗中 有多組複選框或單選按 鈕,就需要視覺化的形 式指明哪些按鈕屬於同 一組。Swing提供了一 組很有用的邊框

(5)如果有多個選擇項,使用單選按鈕佔據的螢幕空 間太大時,就可以選擇組合框。

faceCombo = new JComboBox(); faceCombo.setEditable(true);

讓組合框可編輯 faceCombo.addItem("Serif"); faceCombo.insertItemAt("Monospace",0);

增加組合框選項 faceCombo.removeItem("Monospace");

faceCombo.removeItemAt(0); 刪除組合框選項內容

(6)組合框的事件監聽:為了判斷組合框的哪個選項被選擇,可通過 事件引數呼叫getSource方法來得到傳送事件的組 合框引用,接著呼叫getSelectdeItem方法獲取當 前選擇的選項。

(7)滑動條:滑動條可以讓使用者從一組離散值中進行選擇 ,並且它還允許進行連續值得選擇。

 選單

選單建立  選單項中的圖示  複選框和單選按鈕選單項  彈出選單  快捷鍵和加速器  啟用和禁用選單項  工具欄  工具提示

網格組佈局 (GridBagLayout):GridBagLayout與GridLayout有點相似,它也是 將元件排在格子裡,但是GridBagLayout在網格 的基礎上提供更復雜的佈局。

GridBagLayout允許單個元件在一個單元中不填 滿整個單元,而只是佔用最佳大小,也允許單個 元件擴充套件成不止一個單元,並且可以用任意順序 加入元件。

定製佈局管理器: 程式設計師可通過自己設計LayoutManager類來實現 特殊的佈局方式。

定製佈局管理器需要實現LayoutManager介面, 並覆蓋以下方法。

 對話方塊

選項對話方塊   建立對話方塊   資料選擇   檔案對話方塊  顏色選擇器

(1)對話方塊是一種大小不能變化、不能有選單的容器視窗; 對話方塊不能作為一個應用程式的主框架,而必須包含在其 他的容器中。

(2)選項對話方塊:JOptionPane提供的對話方塊是模式對話方塊。當模 式對話方塊顯示時,它不允許使用者輸入到程式的 其他的視窗。使用JOptionPane,可以建立和自 定義問題、資訊、警告和錯誤等幾種型別的對 話框。

(3)資料交換:輸入對話方塊含有供使用者輸入文字的文字框、一個確認和取 消按鈕,是有模式對話方塊。當輸入對話方塊可見時,要求使用者 輸入一個字串。

(4)檔案對話方塊:專門用於對檔案(或目錄)進行瀏覽和選擇的對 話框,常用的構造方法: – JFileChooser():根據使用者的預設目錄建立檔案對話方塊 – JFileChooser(File currentDirectory):根據File型引數 currentDirectory指定的目錄建立檔案對話方塊

(5)顏色對話方塊: javax.swing包中的JColorChooser類的靜態方 法: public static Color showDialog(Component component, String title, Color initialColor)建立一個顏色對話方塊

(6)引數component指定對話方塊所依賴的元件,title 指定對話方塊的標題;initialColor 指定對話方塊返回 的初始顏色,即對話方塊消失後,返回的預設值。 顏色對話方塊可根據使用者在顏色對話方塊中選擇的顏 色返回一個顏色物件.

二、實驗內容和步驟

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

測試程式1

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

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

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

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

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用來顯示一個演算法的結果
      display.setEnabled(false);
      add(display, BorderLayout.NORTH);
      //定義了兩個監聽器物件
      ActionListener insert = new InsertAction();
      ActionListener command = new CommandAction();

      // add the buttons in a 4 x 4 grid

      panel = new JPanel();//容器元件
      panel.setLayout(new GridLayout(4, 4));//四行四列的網格
     //呼叫addButton方法來新增按鈕
      addButton("3", insert);
      addButton("6", insert);
      addButton("9", insert);
      addButton("/", command);

      addButton("2", insert);
      addButton("5", insert);
      addButton("8", insert);
      addButton("*", command);

      addButton("1", insert);
      addButton("4", insert);
      addButton("7", insert);
      addButton("-", command);

      addButton("0", insert);
      addButton(".", insert);
      addButton("=", command);
      addButton("+", command);
      //建立了16個事件源

      add(panel, BorderLayout.SOUTH);
      JButton b1= new JButton("驗證");
      add(b1, BorderLayout.CENTER);
   }

   /**
    * Adds a button to the center panel.
    * @param label the button label
    * @param listener the button listener
    */
   private void addButton(String label, ActionListener listener)
   {
      JButton button = new JButton(label);
      button.addActionListener(listener);
      panel.add(button);
   }

   /**
    * This action inserts the button action string to the end of the display text.
    */
   private class InsertAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         String input = event.getActionCommand();//通過事件源來獲得動作
         if (start)
         {
            display.setText("");//用setText方法 來更改
            start = false;
         }
         display.setText(display.getText() + input);
      }
   }

   /**
    * This action executes the command that the button action string denotes.
    */
   private class CommandAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         String command = event.getActionCommand();

         if (start)
         {
            if (command.equals("-"))
            {
               display.setText(command);
               start = false;
            }
            else lastCommand = command;
         }
         else
         {
            calculate(Double.parseDouble(display.getText()));
            //將數字字串轉換成對應的數字,用parseDouble
            lastCommand = command;//控制變數
            start = true;
         }
      }
   }

   /**
    * Carries out the pending calculation.
    * @param x the value to be accumulated with the prior result.
    */
   public void calculate(double x)
   {
      if (lastCommand.equals("+")) result += x;
      else if (lastCommand.equals("-")) result -= x;
      else if (lastCommand.equals("*")) result *= x;
      else if (lastCommand.equals("/")) result /= x;
      else if (lastCommand.equals("=")) result = x;
      display.setText("" + result);//""的意義在於字串的轉換
   }
}
package calculator;

import javax.swing.*;

/**
 * A frame with a calculator panel.
 */
public class CalculatorFrame extends JFrame
{
   public CalculatorFrame()
   {
      add(new CalculatorPanel());
      pack();//用pack方法
   }
}
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);//可見的
      });
   }
}

結果如下:

測試程式2

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

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

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

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();//構造一個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);//add方法

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

      add(scrollPane, BorderLayout.CENTER);

      // add button to append text into the text area

      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();
   }
}
Text
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();//生成 TextComponentFrame類的GUI介面物件
         frame.setTitle("TextComponentTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//關閉介面的按鈕操作
         frame.setVisible(true);//使結果可見的
      });
   }
}
text

結果如下:

 

測試程式3

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

l 掌握複選框元件的用法;

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

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

      // this listener sets the font attribute of
      // the label to the check box state

      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));//設定面板中的字型
      };

      // add the check boxes

      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();//調整此視窗的大小
   }
}


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");//設定Title為複選框
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}
CheckBoxTest

結果如下:

測試程式4

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

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

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

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()
   {      
      // add the sample text label

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

      // this listener sets the label font size
      //這個監聽器設定標籤字型大小

      ActionListener listener = event -> label.setFont(new Font("Serif", Font.PLAIN, size));//表明新的字型,大小

      button.addActionListener(listener);
   }
}
radioButton

結果如下:

測試程式5

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

l 掌握邊框的用法;

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

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


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

測試程式6

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

l 掌握組合框元件的用法;

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

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()
   {
      // add the sample text label

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

      // make a combo box and add face names
      //呼叫addItem方法新增選項
      faceCombo = new JComboBox<>();
      faceCombo.addItem("Serif");
      faceCombo.addItem("SansSerif");
      faceCombo.addItem("Monospaced");
      faceCombo.addItem("Dialog");
      faceCombo.addItem("DialogInput");

      // the combo box listener changes the label font to the selected face name

      faceCombo.addActionListener(event ->//組合框產生一個動作事件
         label.setFont(
            new Font(faceCombo.getItemAt(faceCombo.getSelectedIndex()), 
               Font.PLAIN, DEFAULT_SIZE)));

      // add combo box to a panel at the frame's southern border

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

 

測試程式7

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

l 掌握滑動條元件的用法;

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

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

      // common listener for all sliders
      listener = event -> {
         // update text field when the slider value changes
         JSlider source = (JSlider) event.getSource();
         textField.setText("" + source.getValue());
      };

      // add a plain slider
      //新增一個普通滑塊

      JSlider slider = new JSlider();//構造一個滑動條
      addSlider(slider, "Plain");

      // add a slider with major and minor ticks
      
       //新增一個有大和小刻度的滑塊
      slider = new JSlider();
      slider.setPaintTicks(true);
      slider.setMajorTickSpacing(20);
      slider.setMinorTickSpacing(5);
      addSlider(slider, "Ticks");

      // add a slider that snaps to ticks

      slider = new JSlider();
      slider.setPaintTicks(true);//設定標尺標記
      slider.setSnapToTicks(true);
      slider.setMajorTickSpacing(20);//每20個單位的位置顯示一個大標尺標記
      slider.setMinorTickSpacing(5);//每5個單位的位置顯示一個小標尺標記
      addSlider(slider, "Snap to ticks");

      // add a slider with no track
      //新增一個沒有軌道的滑塊
      slider = new JSlider();
      slider.setPaintTicks(true);
      slider.setMajorTickSpacing(20);
      slider.setMinorTickSpacing(5);
      slider.setPaintTrack(false);
      addSlider(slider, "No track");//新增滑塊“無磁塊”

      // add an inverted slider
      //新增一個倒滑塊
      slider = new JSlider();
      slider.setPaintTicks(true);
      slider.setMajorTickSpacing(20);
      slider.setMinorTickSpacing(5);
      slider.setInverted(true);
      addSlider(slider, "Inverted");

      // add a slider with numeric labels

      slider = new JSlider();
      slider.setPaintTicks(true);
      slider.setPaintLabels(true);
      slider.setMajorTickSpacing(20);
      slider.setMinorTickSpacing(5);
      addSlider(slider, "Labels");

      // add a slider with alphabetic 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");

      // add a slider with icon labels
      //新增帶有數字標籤的滑塊

      slider = new JSlider();
      slider.setPaintTicks(true);
      slider.setPaintLabels(true);//滑塊設定面板標籤
      slider.setSnapToTicks(true);
      slider.setMajorTickSpacing(20);
      slider.setMinorTickSpacing(20);

      labelTable = new Hashtable<Integer, Component>();

      // add card images
      
      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");

      // add the text field that displays the slider value

      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);
   }
}
slider
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();//生成 SliderFrame類的GUI介面物件
         frame.setTitle("SliderTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);////關閉介面的按鈕操作
         frame.setVisible(true);//使結果可見
      });
   }
SliderTest

結果:

測試程式8

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

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

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

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

測試程式9(組內實驗)

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

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

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

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);
      }
   }
}
toolbar
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();//生成新的ToolBarFrame類的GUI介面
         frame.setTitle("ToolBarTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//關閉視窗介面
         frame.setVisible(true);//使結果可見
      });
   }
View Code

測試程式10

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

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

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

 

測試程式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;

   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;

      // compute the maximum component widths and heights
      // and set the preferred size to the sum of the component sizes.
      for (int i = 0; i < n; i++)
      {
         Component c = parent.getComponent(i);
         if (c.isVisible())
         {
            Dimension d = c.getPreferredSize();