• 14201771010119穷吉


    实验十四  Swing图形界面组件

     

     

     

    理论知识:

    模型-视图-控制器设计模式(Model –ViewController )是Java EE平台下创建 Web 应用程序 的重要设计模式。

    Java组件有内容、外观、行为三个主要元素;这三个主要元素与模型—视图—控制器模式的 三部件的对应关系为:内容——控制器(作用:处理用户输入)  外观——视图(作用:显示内容)行为——模型(作用:存储内容)

    布局管理器是一组类。实现 java.awt.LayoutManager 接口;决定容器中组件的位置和大小

    Java.awt包中定义了5种布局管理类,每一种布局管理类对应一种布局策略。每个容器都有与之相关的默认布局管理器。当一个容器选定一种布局策略时,它应该创建该 策略对应的布局管理器对象,并将此对象设置为 自己的布局管理器。

    5种布局管理器:(1)FlowLayout:流布局(Applet和Panel的默认布局管理器) (2)BorderLayout:边框布局( Window、Frame和Dialog的默认布局管理器)(3)GridLayout:网格布局(4)GridBagLayout: 网格组布局(5)CardLayout :卡片布局

    FlowLayout Manager 组件采用从左到右,从上到下逐行摆放。

    GridBagLayout不需要组件的尺寸一致,容许组件扩展到多行、多列。

    每个容器对象在没有设置新的布局前,在容器中添加组件都按照该容器的缺省布局排列。通过setLayout( )方法为容器设置新的布局。格式 : 容器组件名.setLayout( 布局类对象名)

    FlowLayout (流布局管理器):用于对组件逐行地定位,每完成一行,一个新行便又开始。与其他布局管理器不同的是,流布局管理器不限制它所管理组件的大小,允许它们有自己的最佳大小。

    文本域(JTextField) : 用于获取单行文本输入。文本域的使用方法:JPanel panel = new JPanel(); JTextField textField = new JTextField("Default input", 20); panel.add(textField);第一个参数“Default input”:将文本域的缺省显示值为Default input ;第二个参数20:表示文本域显示宽度为20列。若要重新设置列数,可使用setColumns方法。

    文本输入常用API:用于文本输入的组件继承于JTextComponent抽象类, java.swing.text.JTextComponent 1.2:String getText() ;  void setText(String text) 获取或设置文本组件中的文本 。 boolean isEditable() ; void setEditable(boolean b) 获取或设置editable特性,这个特性决定了用户是否可以编辑文本组件中的内容。 Java.swing. JComponent : void revalidate( ) :重新计算容器内所有组件的大小和位置,并对它们重新布局。 如 panel.revalidate()

    文本域JTextField常用API : Java.swing. JTextField:  JTextField(int cols) 构造一个指定列数的空JTextField对象。  JTextField(String text,int cols) 构造一个指定列数、指定初始字符串的JTextField对象 。 int getColumns(int cols) ; void setColumns(int cols) 获取或设置文本域使用的列数

    文本区与文本域的异同相同之处: 文本域和文本区组件都可用于获取文本输入。 不同之处:文本域只能接受单行文本的输入;文本区能够接受多行文本的输入。

    标签是容纳文本的组件。它们没有任何修饰(如没有边界 ),也不响应用户输入。标签的常用用途之一就是标识组件,例如标识文本域。其使用步骤如下: 1. 创建一个JLabel组件。例: JLabel label = new JLabel(“hours”, SwingConstants.RIGHT); 或者 JLabel label = new JLabel(“hours”, JLabel.RIGHT);以上代码创建了一个label,并指定label的对齐方式为右对齐。 2. 将标签组件放置在距离被标识组件足够近的地方。

    密码域是一种特殊类型的文本域。每个输入的字符都用回显字符实现,典型的回显字符为*。

    复选框( JCheckBox ):如果想要接收的输入只是“是”或“非”,就可以使用复选框组件。用户通过单击某个复选框来选择相应的选项,再点击则取消选择。当复选框获得焦点时,用户也可以通过空格键来切换选择。

    复选框常用API: 1.void setSelected(boolean state); 设置复选框的选择状态 2.boolean isSelected(); 获取复选框的选择状态

    边框:如果在一个窗口中有多组复选框或单选按 钮,就需要可视化的形式指明哪些按钮属于同 一组。Swing提供了一 组很有用的边框 ( borders)来解决这个问题。

    边框的创建方法:可以调用BorderFactory类的静态方法创建。可选的风格有:凹斜面:BorderFactory.createLoweredBevelBorder() 凸斜面:BorderFactory.createRaisedBevelBorder() 蚀刻:BorderFactory.createEtchedBorder() 直线:BorderFactory.createLineBorder(Color) 不光滑:BorderFactory.createMatteBorder()还可以给边框加标题 BorderFactory.createTitledBorder()

    ;

    1、实验目的与要求

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

    (2) 掌握各类Java Swing组件用途及常用API;

    2、实验内容和步骤

    实验1: 导入第12章示例程序,测试程序并进行组内讨论。

    测试程序1

    在elipse IDE中运行教材479页程序12-1,结合运行结果理解程序;

    掌握各种布局管理器的用法;

    理解GUI界面中事件处理技术的用途。

    在布局管理应用代码处添加注释;

    1 import java.awt.*;
     2 import javax.swing.*;
     3 
     4 /**
     5  * @version 1.34 2015-06-12
     6  * @author Cay Horstmann
     7  */
     8 public class Calculator
     9 {
    10    public static void main(String[] args)
    11    {
    12       EventQueue.invokeLater(() -> {
    13          CalculatorFrame frame = new CalculatorFrame();
    14          frame.setTitle("Calculator");
    15          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    16          frame.setVisible(true);
    17       });
    18    }
    19 }
    复制代码
    复制代码
     1 package calculator;
     2 
     3 import javax.swing.*;
     4 
     5 /**
     6  * 一个带有计算器面板的框架。
     7  */
     8 public class CalculatorFrame extends JFrame
     9 {
    10    public CalculatorFrame()
    11    {
    12       add(new CalculatorPanel());
    13       pack();
    14    }
    15 }
    复制代码
     

    package calculator.copy;

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

    /**
    * A panel with calculator buttons and a result display.
    */
    public class CalculatorPanel extends JPanel
    {
    private JButton display;
    private JPanel panel;
    private double result;
    private String lastCommand;
    private boolean start;

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

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

    // add the display

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

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

    // add the buttons in a 4 x 4 grid

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

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

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

    /**
    * This action inserts the button action string to the end of the display text.
    */
    private class InsertAction implements ActionListener
    {
    public void actionPerformed(ActionEvent event)
    {
    String input = event.getActionCommand();
    if (start)
    {
    display.setText("");
    start = false;
    }
    display.setText(display.getText() + input);
    }
    }

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

    if (start)
    {
    if (command.equals("-"))
    {
    display.setText(command);
    start = false;
    }
    else lastCommand = command;
    }
    else
    {
    calculate(Double.parseDouble(display.getText()));
    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

    在elipse IDE中调试运行教材486页程序12-2,结合运行结果理解程序;

    掌握各种文本组件的用法;

    记录示例代码阅读理解中存在的问题与疑惑。

     package text;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.41 2015-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class TextComponentTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          JFrame frame = new TextComponentFrame();
    16          frame.setTitle("TextComponentTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
     1 package text;
     2 
     3 import java.awt.BorderLayout;
     4 import java.awt.GridLayout;
     5 
     6 import javax.swing.JButton;
     7 import javax.swing.JFrame;
     8 import javax.swing.JLabel;
     9 import javax.swing.JPanel;
    10 import javax.swing.JPasswordField;
    11 import javax.swing.JScrollPane;
    12 import javax.swing.JTextArea;
    13 import javax.swing.JTextField;
    14 import javax.swing.SwingConstants;
    15 
    16 /**
    17  * 具有文本文本组件的框架.
    18  */
    19 public class TextComponentFrame extends JFrame
    20 {
    21    public static final int TEXTAREA_ROWS = 8;
    22    public static final int TEXTAREA_COLUMNS = 20;
    23 
    24    public TextComponentFrame()
    25    {
    26       JTextField textField = new JTextField();
    27       JPasswordField passwordField = new JPasswordField();
    28 
    29       JPanel northPanel = new JPanel();
    30       northPanel.setLayout(new GridLayout(2, 2));
    31       northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT));
    32       northPanel.add(textField);
    33       northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT));
    34       northPanel.add(passwordField);
    35 
    36       add(northPanel, BorderLayout.NORTH);
    37 
    38       JTextArea textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS);
    39       JScrollPane scrollPane = new JScrollPane(textArea);
    40 
    41       add(scrollPane, BorderLayout.CENTER);
    42 
    43       // 添加按钮将文本追加到文本区域
    44 
    45       JPanel southPanel = new JPanel();
    46 
    47       JButton insertButton = new JButton("Insert");
    48       southPanel.add(insertButton);
    49       insertButton.addActionListener(event ->
    50          textArea.append("User name: " + textField.getText() + " Password: "
    51             + new String(passwordField.getPassword()) + "
    "));
    52 
    53       add(southPanel, BorderLayout.SOUTH);
    54       pack();
    55    }
    56 }
    
    

    测试程序3

    在elipse IDE中调试运行教材489页程序12-3,结合运行结果理解程序;

    掌握复选框组件的用法;

    记录示例代码阅读理解中存在的问题与疑惑。

    package checkBox;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.34 2015-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class CheckBoxTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          JFrame frame = new CheckBoxFrame();
    16          frame.setTitle("CheckBoxTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
     1 package checkBox;
     2 
     3 import java.awt.*;
     4 import java.awt.event.*;
     5 import javax.swing.*;
     6 
     7 /**
     8  * 带有样本文本标签的框和用于选择字体的复选框
     9  * attributes.
    10  */
    11 public class CheckBoxFrame extends JFrame
    12 {
    13    private JLabel label;
    14    private JCheckBox bold;
    15    private JCheckBox italic;
    16    private static final int FONTSIZE = 24;
    17 
    18    public CheckBoxFrame()
    19    {
    20       // 添加示例文本标签
    21 
    22       label = new JLabel("The quick brown fox jumps over the lazy dog.");
    23       label.setFont(new Font("Serif", Font.BOLD, FONTSIZE));
    24       add(label, BorderLayout.CENTER);
    25 
    26       // 此侦听器设置字体属性
    27       // 到复选框状态的标签
    28 
    29       ActionListener listener = event -> {
    30          int mode = 0;
    31          if (bold.isSelected()) mode += Font.BOLD;
    32          if (italic.isSelected()) mode += Font.ITALIC;
    33          label.setFont(new Font("Serif", mode, FONTSIZE));
    34       };
    35 
    36       // 添加复选框
    37 
    38       JPanel buttonPanel = new JPanel();
    39 
    40       bold = new JCheckBox("Bold");
    41       bold.addActionListener(listener);
    42       bold.setSelected(true);
    43       buttonPanel.add(bold);
    44 
    45       italic = new JCheckBox("Italic");
    46       italic.addActionListener(listener);
    47       buttonPanel.add(italic);
    48 
    49       add(buttonPanel, BorderLayout.SOUTH);
    50       pack();
    51    }
    52 }
    
    

    测试程序4

    在elipse IDE中调试运行教材491页程序12-4,运行结果理解程序;

    掌握单选按钮组件的用法;

    记录示例代码阅读理解中存在的问题与疑惑。

     1 package radioButton;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.34 2015-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class RadioButtonTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          JFrame frame = new RadioButtonFrame();
    16          frame.setTitle("RadioButtonTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
     1 package radioButton;
     2 
     3 import java.awt.*;
     4 import java.awt.event.*;
     5 import javax.swing.*;
     6 
     7 /**
     8  * 带有样本文本标签和单选按钮以选择字体大小的框架。
     9  */
    10 public class RadioButtonFrame extends JFrame
    11 {
    12    private JPanel buttonPanel;
    13    private ButtonGroup group;
    14    private JLabel label;
    15    private static final int DEFAULT_SIZE = 36;
    16 
    17    public RadioButtonFrame()
    18    {      
    19       // 添加示例文本标签
    20 
    21       label = new JLabel("The quick brown fox jumps over the lazy dog.");
    22       label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
    23       add(label, BorderLayout.CENTER);
    24 
    25       // 添加单选按钮
    26 
    27       buttonPanel = new JPanel();
    28       group = new ButtonGroup();
    29 
    30       addRadioButton("Small", 8);
    31       addRadioButton("Medium", 12);
    32       addRadioButton("Large", 18);
    33       addRadioButton("Extra large", 36);
    34 
    35       add(buttonPanel, BorderLayout.SOUTH);
    36       pack();
    37    }
    38 
    39    /**
    40     * 添加一个设置示例文本字体大小的单选按钮。
    41     * @param 命名按钮上出现的字符串
    42     * @param 设置此按钮设置的字体大小
    43     */
    44    public void addRadioButton(String name, int size)
    45    {
    46       boolean selected = size == DEFAULT_SIZE;
    47       JRadioButton button = new JRadioButton(name, selected);
    48       group.add(button);
    49       buttonPanel.add(button);
    50 
    51       // 此侦听器设置标签字体大小。
    52       ActionListener listener = event -> label.setFont(new Font("Serif", Font.PLAIN, size));
    53 
    54       button.addActionListener(listener);
    55    }
    56 }
    
    

    测试程序5

    在elipse IDE中调试运行教材494页程序12-5,结合运行结果理解程序;

    掌握边框的用法;

    记录示例代码阅读理解中存在的问题与疑惑。

    1 package border;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.34 2015-06-13
     8  * @author Cay Horstmann
     9  */
    10 public class BorderTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          JFrame frame = new BorderFrame();
    16          frame.setTitle("BorderTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
     1 package border;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 import javax.swing.border.*;
     6 
     7 /**
     8  * 用单选按钮选择边框样式的框架
     9  */
    10 public class BorderFrame extends JFrame
    11 {
    12    private JPanel demoPanel;
    13    private JPanel buttonPanel;
    14    private ButtonGroup group;
    15 
    16    public BorderFrame()
    17    {
    18       demoPanel = new JPanel();
    19       buttonPanel = new JPanel();
    20       group = new ButtonGroup();
    21 
    22       addRadioButton("Lowered bevel", BorderFactory.createLoweredBevelBorder());
    23       addRadioButton("Raised bevel", BorderFactory.createRaisedBevelBorder());
    24       addRadioButton("Etched", BorderFactory.createEtchedBorder());
    25       addRadioButton("Line", BorderFactory.createLineBorder(Color.BLUE));
    26       addRadioButton("Matte", BorderFactory.createMatteBorder(10, 10, 10, 10, Color.BLUE));
    27       addRadioButton("Empty", BorderFactory.createEmptyBorder());
    28 
    29       Border etched = BorderFactory.createEtchedBorder();
    30       Border titled = BorderFactory.createTitledBorder(etched, "Border types");
    31       buttonPanel.setBorder(titled);
    32 
    33       setLayout(new GridLayout(2, 1));
    34       add(buttonPanel);
    35       add(demoPanel);
    36       pack();
    37    }
    38 
    39    public void addRadioButton(String buttonName, Border b)
    40    {
    41       JRadioButton button = new JRadioButton(buttonName);
    42       button.addActionListener(event -> demoPanel.setBorder(b));
    43       group.add(button);
    44       buttonPanel.add(button);
    45    }
    46 }
    
    

    测试程序6

    在elipse IDE中调试运行教材498页程序12-6,结合运行结果理解程序;

    掌握组合框组件的用法;

    记录示例代码阅读理解中存在的问题与疑惑。

    1 package comboBox;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.35 2015-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class ComboBoxTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          JFrame frame = new ComboBoxFrame();
    16          frame.setTitle("ComboBoxTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
     1 package comboBox;
     2 
     3 import java.awt.BorderLayout;
     4 import java.awt.Font;
     5 
     6 import javax.swing.JComboBox;
     7 import javax.swing.JFrame;
     8 import javax.swing.JLabel;
     9 import javax.swing.JPanel;
    10 
    11 /**
    12  * 具有样本文本标签和选择字体面的组合框的框架。
    13  */
    14 public class ComboBoxFrame extends JFrame
    15 {
    16    private JComboBox<String> faceCombo;
    17    private JLabel label;
    18    private static final int DEFAULT_SIZE = 24;
    19 
    20    public ComboBoxFrame()
    21    {
    22       // 添加示例文本标签
    23 
    24       label = new JLabel("The quick brown fox jumps over the lazy dog.");
    25       label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
    26       add(label, BorderLayout.CENTER);
    27 
    28       // 制作组合框并添加面部名称
    29 
    30       faceCombo = new JComboBox<>();
    31       faceCombo.addItem("Serif");
    32       faceCombo.addItem("SansSerif");
    33       faceCombo.addItem("Monospaced");
    34       faceCombo.addItem("Dialog");
    35       faceCombo.addItem("DialogInput");
    36 
    37       // 组合框侦听器将标签字体更改为选定的面部名称。
    38 
    39       faceCombo.addActionListener(event ->
    40          label.setFont(
    41             new Font(faceCombo.getItemAt(faceCombo.getSelectedIndex()), 
    42                Font.PLAIN, DEFAULT_SIZE)));
    43 
    44       // 将组合框添加到框架的南部边界的面板上
    45 
    46       JPanel comboPanel = new JPanel();
    47       comboPanel.add(faceCombo);
    48       add(comboPanel, BorderLayout.SOUTH);
    49       pack();
    50    }
    51 }
    
    

    测试程序7

    在elipse IDE中调试运行教材501页程序12-7,结合运行结果理解程序;

    掌握滑动条组件的用法;

    记录示例代码阅读理解中存在的问题与疑惑。

     1 package slider;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.15 2015-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class SliderTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          SliderFrame frame = new SliderFrame();
    16          frame.setTitle("SliderTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
      1 package slider;
      2 
      3 import java.awt.*;
      4 import java.util.*;
      5 import javax.swing.*;
      6 import javax.swing.event.*;
      7 
      8 /**
      9  * 一个具有许多滑块和文本字段的滑块值的框架。
     10  */
     11 public class SliderFrame extends JFrame
     12 {
     13    private JPanel sliderPanel;
     14    private JTextField textField;
     15    private ChangeListener listener;
     16 
     17    public SliderFrame()
     18    {
     19       sliderPanel = new JPanel();
     20       sliderPanel.setLayout(new GridBagLayout());
     21 
     22       // 所有滑块的公用侦听器
     23       listener = event -> {
     24          // 当滑块值改变时更新文本字段
     25          JSlider source = (JSlider) event.getSource();
     26          textField.setText("" + source.getValue());
     27       };
     28 
     29       // 添加普通滑块
     30 
     31       JSlider slider = new JSlider();
     32       addSlider(slider, "Plain");
     33 
     34       // 添加有主和小蜱的滑块
     35 
     36       slider = new JSlider();
     37       slider.setPaintTicks(true);
     38       slider.setMajorTickSpacing(20);
     39       slider.setMinorTickSpacing(5);
     40       addSlider(slider, "Ticks");
     41 
     42       // 添加一个滑动到滴答的滑块
     43       slider = new JSlider();
     44       slider.setPaintTicks(true);
     45       slider.setSnapToTicks(true);
     46       slider.setMajorTickSpacing(20);
     47       slider.setMinorTickSpacing(5);
     48       addSlider(slider, "Snap to ticks");
     49 
     50       // 添加没有磁道的滑块
     51 
     52       slider = new JSlider();
     53       slider.setPaintTicks(true);
     54       slider.setMajorTickSpacing(20);
     55       slider.setMinorTickSpacing(5);
     56       slider.setPaintTrack(false);
     57       addSlider(slider, "No track");
     58 
     59       // 添加倒置滑块
     60       slider = new JSlider();
     61       slider.setPaintTicks(true);
     62       slider.setMajorTickSpacing(20);
     63       slider.setMinorTickSpacing(5);
     64       slider.setInverted(true);
     65       addSlider(slider, "Inverted");
     66 
     67       // 添加带有数字标签的滑块
     68 
     69       slider = new JSlider();
     70       slider.setPaintTicks(true);
     71       slider.setPaintLabels(true);
     72       slider.setMajorTickSpacing(20);
     73       slider.setMinorTickSpacing(5);
     74       addSlider(slider, "Labels");
     75 
     76       // 添加带有字母标签的滑块
     77       slider = new JSlider();
     78       slider.setPaintLabels(true);
     79       slider.setPaintTicks(true);
     80       slider.setMajorTickSpacing(20);
     81       slider.setMinorTickSpacing(5);
     82 
     83       Dictionary<Integer, Component> labelTable = new Hashtable<>();
     84       labelTable.put(0, new JLabel("A"));
     85       labelTable.put(20, new JLabel("B"));
     86       labelTable.put(40, new JLabel("C"));
     87       labelTable.put(60, new JLabel("D"));
     88       labelTable.put(80, new JLabel("E"));
     89       labelTable.put(100, new JLabel("F"));
     90 
     91       slider.setLabelTable(labelTable);
     92       addSlider(slider, "Custom labels");
     93 
     94       // 添加带有图标标签的滑块
     95 
     96       slider = new JSlider();
     97       slider.setPaintTicks(true);
     98       slider.setPaintLabels(true);
     99       slider.setSnapToTicks(true);
    100       slider.setMajorTickSpacing(20);
    101       slider.setMinorTickSpacing(20);
    102 
    103       labelTable = new Hashtable<Integer, Component>();
    104 
    105       // 添加卡片图像
    106 
    107       labelTable.put(0, new JLabel(new ImageIcon("nine.gif")));
    108       labelTable.put(20, new JLabel(new ImageIcon("ten.gif")));
    109       labelTable.put(40, new JLabel(new ImageIcon("jack.gif")));
    110       labelTable.put(60, new JLabel(new ImageIcon("queen.gif")));
    111       labelTable.put(80, new JLabel(new ImageIcon("king.gif")));
    112       labelTable.put(100, new JLabel(new ImageIcon("ace.gif")));
    113 
    114       slider.setLabelTable(labelTable);
    115       addSlider(slider, "Icon labels");
    116 
    117       // 添加显示滑块值的文本字段
    118 
    119       textField = new JTextField();
    120       add(sliderPanel, BorderLayout.CENTER);
    121       add(textField, BorderLayout.SOUTH);
    122       pack();
    123    }
    124 
    125    /**
    126     * 向滑块面板添加滑块并钩住听者
    127     * @param S滑块
    128     * @param 描述滑块描述
    129     */
    130    public void addSlider(JSlider s, String description)
    131    {
    132       s.addChangeListener(listener);
    133       JPanel panel = new JPanel();
    134       panel.add(s);
    135       panel.add(new JLabel(description));
    136       panel.setAlignmentX(Component.LEFT_ALIGNMENT);
    137       GridBagConstraints gbc = new GridBagConstraints();
    138       gbc.gridy = sliderPanel.getComponentCount();
    139       gbc.anchor = GridBagConstraints.WEST;
    140       sliderPanel.add(panel, gbc);
    141    }
    142 }

    
    

    测试程序8

    在elipse IDE中调试运行教材512页程序12-8,结合运行结果理解程序;

    掌握菜单的创建、菜单事件监听器、复选框和单选按钮菜单项、弹出菜单以及快捷键和加速器的用法。

    记录示例代码阅读理解中存在的问题与疑惑。

     1 package menu;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.24 2012-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class MenuTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          JFrame frame = new MenuFrame();
    16          frame.setTitle("MenuTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
      1 package menu;
      2 
      3 import java.awt.event.*;
      4 import javax.swing.*;
      5 
      6 /**
      7  * 一个带有示例菜单栏的框架。
      8  */
      9 public class MenuFrame extends JFrame
     10 {
     11    private static final int DEFAULT_WIDTH = 300;
     12    private static final int DEFAULT_HEIGHT = 200;
     13    private Action saveAction;
     14    private Action saveAsAction;
     15    private JCheckBoxMenuItem readonlyItem;
     16    private JPopupMenu popup;
     17 
     18    /**
     19     * 将动作名称打印到Studio.OUT的示例动作。
     20     */
     21    class TestAction extends AbstractAction
     22    {
     23       public TestAction(String name)
     24       {
     25          super(name);
     26       }
     27 
     28       public void actionPerformed(ActionEvent event)
     29       {
     30          System.out.println(getValue(Action.NAME) + " selected.");
     31       }
     32    }
     33 
     34    public MenuFrame()
     35    {
     36       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
     37 
     38       JMenu fileMenu = new JMenu("File");
     39       fileMenu.add(new TestAction("New"));
     40 
     41       // 演示加速器
     42       JMenuItem openItem = fileMenu.add(new TestAction("Open"));
     43       openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
     44 
     45       fileMenu.addSeparator();
     46 
     47       saveAction = new TestAction("Save");
     48       JMenuItem saveItem = fileMenu.add(saveAction);
     49       saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
     50 
     51       saveAsAction = new TestAction("Save As");
     52       fileMenu.add(saveAsAction);
     53       fileMenu.addSeparator();
     54 
     55       fileMenu.add(new AbstractAction("Exit")
     56          {
     57             public void actionPerformed(ActionEvent event)
     58             {
     59                System.exit(0);
     60             }
     61          });
     62 
     63       // 演示复选框和单选按钮菜单
     64 
     65       readonlyItem = new JCheckBoxMenuItem("Read-only");
     66       readonlyItem.addActionListener(new ActionListener()
     67          {
     68             public void actionPerformed(ActionEvent event)
     69             {
     70                boolean saveOk = !readonlyItem.isSelected();
     71                saveAction.setEnabled(saveOk);
     72                saveAsAction.setEnabled(saveOk);
     73             }
     74          });
     75 
     76       ButtonGroup group = new ButtonGroup();
     77 
     78       JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert");
     79       insertItem.setSelected(true);
     80       JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype");
     81 
     82       group.add(insertItem);
     83       group.add(overtypeItem);
     84 
     85       // 演示图标
     86 
     87       Action cutAction = new TestAction("Cut");
     88       cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
     89       Action copyAction = new TestAction("Copy");
     90       copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif"));
     91       Action pasteAction = new TestAction("Paste");
     92       pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif"));
     93 
     94       JMenu editMenu = new JMenu("Edit");
     95       editMenu.add(cutAction);
     96       editMenu.add(copyAction);
     97       editMenu.add(pasteAction);
     98 
     99       // 演示嵌套菜单
    100 
    101       JMenu optionMenu = new JMenu("Options");
    102 
    103       optionMenu.add(readonlyItem);
    104       optionMenu.addSeparator();
    105       optionMenu.add(insertItem);
    106       optionMenu.add(overtypeItem);
    107 
    108       editMenu.addSeparator();
    109       editMenu.add(optionMenu);
    110 
    111       // 助记符演示
    112 
    113       JMenu helpMenu = new JMenu("Help");
    114       helpMenu.setMnemonic('H');
    115 
    116       JMenuItem indexItem = new JMenuItem("Index");
    117       indexItem.setMnemonic('I');
    118       helpMenu.add(indexItem);
    119 
    120       // 还可以将助记键添加到动作中。
    121       Action aboutAction = new TestAction("About");
    122       aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));
    123       helpMenu.add(aboutAction);
    124       
    125       // 将所有顶级菜单添加到菜单栏
    126 
    127       JMenuBar menuBar = new JMenuBar();
    128       setJMenuBar(menuBar);
    129 
    130       menuBar.add(fileMenu);
    131       menuBar.add(editMenu);
    132       menuBar.add(helpMenu);
    133 
    134       // 演示弹出窗口
    135 
    136       popup = new JPopupMenu();
    137       popup.add(cutAction);
    138       popup.add(copyAction);
    139       popup.add(pasteAction);
    140 
    141       JPanel panel = new JPanel();
    142       panel.setComponentPopupMenu(popup);
    143       add(panel);
    144    }
    145 }

    
    
    
    

    测试程序9

    在elipse IDE中调试运行教材517页程序12-9,结合运行结果理解程序;

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

    记录示例代码阅读理解中存在的问题与疑惑。

    1 package toolBar;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.14 2015-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class ToolBarTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          ToolBarFrame frame = new ToolBarFrame();
    16          frame.setTitle("ToolBarTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
     1 package toolBar;
     2 
     3 import java.awt.*;
     4 import java.awt.event.*;
     5 import javax.swing.*;
     6 
     7 /**
     8  * 带有工具栏和菜单的框架,用于颜色变化。
     9  */
    10 public class ToolBarFrame extends JFrame
    11 {
    12    private static final int DEFAULT_WIDTH = 300;
    13    private static final int DEFAULT_HEIGHT = 200;
    14    private JPanel panel;
    15 
    16    public ToolBarFrame()
    17    {
    18       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    19 
    20       // 添加颜色变化面板
    21 
    22       panel = new JPanel();
    23       add(panel, BorderLayout.CENTER);
    24 
    25       // 设置动作
    26       Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
    27       Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
    28             Color.YELLOW);
    29       Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
    30 
    31       Action exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif"))
    32          {
    33             public void actionPerformed(ActionEvent event)
    34             {
    35                System.exit(0);
    36             }
    37          };
    38       exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");
    39 
    40       // 填充工具栏
    41 
    42       JToolBar bar = new JToolBar();
    43       bar.add(blueAction);
    44       bar.add(yellowAction);
    45       bar.add(redAction);
    46       bar.addSeparator();
    47       bar.add(exitAction);
    48       add(bar, BorderLayout.NORTH);
    49 
    50       // 填充菜单
    51 
    52       JMenu menu = new JMenu("Color");
    53       menu.add(yellowAction);
    54       menu.add(blueAction);
    55       menu.add(redAction);
    56       menu.add(exitAction);
    57       JMenuBar menuBar = new JMenuBar();
    58       menuBar.add(menu);
    59       setJMenuBar(menuBar);
    60    }
    61 
    62    /**
    63     * 颜色动作将帧的背景设置为给定的颜色。
    64     */
    65    class ColorAction extends AbstractAction
    66    {
    67       public ColorAction(String name, Icon icon, Color c)
    68       {
    69          putValue(Action.NAME, name);
    70          putValue(Action.SMALL_ICON, icon);
    71          putValue(Action.SHORT_DESCRIPTION, name + " background");
    72          putValue("Color", c);
    73       }
    74 
    75       public void actionPerformed(ActionEvent event)
    76       {
    77          Color c = (Color) getValue("Color");
    78          panel.setBackground(c);
    79       }
    80    }
    81 }
    
    

    测试程序10

    在elipse IDE中调试运行教材524页程序12-10、12-11,结合运行结果理解程序,了解GridbagLayout的用法。

    1 package gridbag;
     2 
     3 import java.awt.EventQueue;
     4 
     5 import javax.swing.JFrame;
     6 
     7 /**
     8  * @version 1.35 2015-06-12
     9  * @author Cay Horstmann
    10  */
    11 public class GridBagLayoutTest
    12 {
    13    public static void main(String[] args)
    14    {
    15       EventQueue.invokeLater(() ->           {
    16                JFrame frame = new FontFrame();
    17                frame.setTitle("GridBagLayoutTest");
    18                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    19                frame.setVisible(true);
    20          });
    21    }
    22 }
    复制代码
    复制代码
      1 package gridbag;
      2 
      3 import java.awt.*;
      4 
      5 /**
      6  * This class simplifies the use of the GridBagConstraints class.
      7  * @version 1.01 2004-05-06
      8  * @author Cay Horstmann
      9  */
     10 public class GBC extends GridBagConstraints
     11 {
     12    /**
     13     * Constructs a GBC with a given gridx and gridy position and all other grid
     14     * bag constraint values set to the default.
     15     * @param gridx the gridx position
     16     * @param gridy the gridy position
     17     */
     18    public GBC(int gridx, int gridy)
     19    {
     20       this.gridx = gridx;
     21       this.gridy = gridy;
     22    }
     23 
     24    /**
     25     * Constructs a GBC with given gridx, gridy, gridwidth, gridheight and all
     26     * other grid bag constraint values set to the default.
     27     * @param gridx the gridx position
     28     * @param gridy the gridy position
     29     * @param gridwidth the cell span in x-direction
     30     * @param gridheight the cell span in y-direction
     31     */
     32    public GBC(int gridx, int gridy, int gridwidth, int gridheight)
     33    {
     34       this.gridx = gridx;
     35       this.gridy = gridy;
     36       this.gridwidth = gridwidth;
     37       this.gridheight = gridheight;
     38    }
     39 
     40    /**
     41     * Sets the anchor.
     42     * @param anchor the anchor value
     43     * @return this object for further modification
     44     */
     45    public GBC setAnchor(int anchor)
     46    {
     47       this.anchor = anchor;
     48       return this;
     49    }
     50 
     51    /**
     52     * Sets the fill direction.
     53     * @param fill the fill direction
     54     * @return this object for further modification
     55     */
     56    public GBC setFill(int fill)
     57    {
     58       this.fill = fill;
     59       return this;
     60    }
     61 
     62    /**
     63     * Sets the cell weights.
     64     * @param weightx the cell weight in x-direction
     65     * @param weighty the cell weight in y-direction
     66     * @return this object for further modification
     67     */
     68    public GBC setWeight(double weightx, double weighty)
     69    {
     70       this.weightx = weightx;
     71       this.weighty = weighty;
     72       return this;
     73    }
     74 
     75    /**
     76     * Sets the insets of this cell.
     77     * @param distance the spacing to use in all directions
     78     * @return this object for further modification
     79     */
     80    public GBC setInsets(int distance)
     81    {
     82       this.insets = new Insets(distance, distance, distance, distance);
     83       return this;
     84    }
     85 
     86    /**
     87     * Sets the insets of this cell.
     88     * @param top the spacing to use on top
     89     * @param left the spacing to use to the left
     90     * @param bottom the spacing to use on the bottom
     91     * @param right the spacing to use to the right
     92     * @return this object for further modification
     93     */
     94    public GBC setInsets(int top, int left, int bottom, int right)
     95    {
     96       this.insets = new Insets(top, left, bottom, right);
     97       return this;
     98    }
     99 
    100    /**
    101     * Sets the internal padding
    102     * @param ipadx the internal padding in x-direction
    103     * @param ipady the internal padding in y-direction
    104     * @return this object for further modification
    105     */
    106    public GBC setIpad(int ipadx, int ipady)
    107    {
    108       this.ipadx = ipadx;
    109       this.ipady = ipady;
    110       return this;
    111    }
    112 }
    复制代码
    复制代码
     1 package gridbag;
     2 
     3 import java.awt.Font;
     4 import java.awt.GridBagLayout;
     5 import java.awt.event.ActionListener;
     6 
     7 import javax.swing.BorderFactory;
     8 import javax.swing.JCheckBox;
     9 import javax.swing.JComboBox;
    10 import javax.swing.JFrame;
    11 import javax.swing.JLabel;
    12 import javax.swing.JTextArea;
    13 
    14 /**
    15  * A frame that uses a grid bag layout to arrange font selection components.
    16  */
    17 public class FontFrame extends JFrame
    18 {
    19    public static final int TEXT_ROWS = 10;
    20    public static final int TEXT_COLUMNS = 20;
    21 
    22    private JComboBox<String> face;
    23    private JComboBox<Integer> size;
    24    private JCheckBox bold;
    25    private JCheckBox italic;
    26    private JTextArea sample;
    27 
    28    public FontFrame()
    29    {
    30       GridBagLayout layout = new GridBagLayout();
    31       setLayout(layout);
    32 
    33       ActionListener listener = event -> updateSample();
    34 
    35       // construct components
    36 
    37       JLabel faceLabel = new JLabel("Face: ");
    38 
    39       face = new JComboBox<>(new String[] { "Serif", "SansSerif", "Monospaced",
    40             "Dialog", "DialogInput" });
    41 
    42       face.addActionListener(listener);
    43 
    44       JLabel sizeLabel = new JLabel("Size: ");
    45 
    46       size = new JComboBox<>(new Integer[] { 8, 10, 12, 15, 18, 24, 36, 48 });
    47 
    48       size.addActionListener(listener);
    49 
    50       bold = new JCheckBox("Bold");
    51       bold.addActionListener(listener);
    52 
    53       italic = new JCheckBox("Italic");
    54       italic.addActionListener(listener);
    55 
    56       sample = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
    57       sample.setText("The quick brown fox jumps over the lazy dog");
    58       sample.setEditable(false);
    59       sample.setLineWrap(true);
    60       sample.setBorder(BorderFactory.createEtchedBorder());
    61 
    62       // add components to grid, using GBC convenience class
    63 
    64       add(faceLabel, new GBC(0, 0).setAnchor(GBC.EAST));
    65       add(face, new GBC(1, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0)
    66             .setInsets(1));
    67       add(sizeLabel, new GBC(0, 1).setAnchor(GBC.EAST));
    68       add(size, new GBC(1, 1).setFill(GBC.HORIZONTAL).setWeight(100, 0)
    69             .setInsets(1));
    70       add(bold, new GBC(0, 2, 2, 1).setAnchor(GBC.CENTER).setWeight(100, 100));
    71       add(italic, new GBC(0, 3, 2, 1).setAnchor(GBC.CENTER).setWeight(100, 100));
    72       add(sample, new GBC(2, 0, 1, 4).setFill(GBC.BOTH).setWeight(100, 100));
    73       pack();
    74       updateSample();
    75    }
    76 
    77    public void updateSample()
    78    {
    79       String fontFace = (String) face.getSelectedItem();
    80       int fontStyle = (bold.isSelected() ? Font.BOLD : 0)
    81             + (italic.isSelected() ? Font.ITALIC : 0);
    82       int fontSize = size.getItemAt(size.getSelectedIndex());
    83       Font font = new Font(fontFace, fontStyle, fontSize);
    84       sample.setFont(font);
    85       sample.repaint();
    86    }
    87 }
    
    

    在elipse IDE中调试运行教材533页程序12-12,结合程序运行结果理解程序,了解GroupLayout的用法。

    记录示例代码阅读理解中存在的问题与疑惑。

    1 package groupLayout;
     2 
     3 import java.awt.EventQueue;
     4 
     5 import javax.swing.JFrame;
     6 
     7 /**
     8  * @version 1.01 2015-06-12
     9  * @author Cay Horstmann
    10  */
    11 public class GroupLayoutTest
    12 {
    13    public static void main(String[] args)
    14    {
    15       EventQueue.invokeLater(() -> {
    16          JFrame frame = new FontFrame();
    17          frame.setTitle("GroupLayoutTest");
    18          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    19          frame.setVisible(true);
    20       });
    21    }
    22 }
    复制代码
    复制代码
      1 package groupLayout;
      2 
      3 import java.awt.Font;
      4 import java.awt.event.ActionListener;
      5 
      6 import javax.swing.BorderFactory;
      7 import javax.swing.GroupLayout;
      8 import javax.swing.JCheckBox;
      9 import javax.swing.JComboBox;
     10 import javax.swing.JFrame;
     11 import javax.swing.JLabel;
     12 import javax.swing.JScrollPane;
     13 import javax.swing.JTextArea;
     14 import javax.swing.LayoutStyle;
     15 import javax.swing.SwingConstants;
     16 
     17 /**
     18  * A frame that uses a group layout to arrange font selection components.
     19  */
     20 public class FontFrame extends JFrame
     21 {
     22    public static final int TEXT_ROWS = 10;
     23    public static final int TEXT_COLUMNS = 20;
     24 
     25    private JComboBox<String> face;
     26    private JComboBox<Integer> size;
     27    private JCheckBox bold;
     28    private JCheckBox italic;
     29    private JScrollPane pane;
     30    private JTextArea sample;
     31 
     32    public FontFrame()
     33    {
     34       ActionListener listener = event -> updateSample(); 
     35 
     36       // construct components
     37 
     38       JLabel faceLabel = new JLabel("Face: ");
     39 
     40       face = new JComboBox<>(new String[] { "Serif", "SansSerif", "Monospaced", "Dialog",
     41             "DialogInput" });
     42 
     43       face.addActionListener(listener);
     44 
     45       JLabel sizeLabel = new JLabel("Size: ");
     46 
     47       size = new JComboBox<>(new Integer[] { 8, 10, 12, 15, 18, 24, 36, 48 });
     48 
     49       size.addActionListener(listener);
     50 
     51       bold = new JCheckBox("Bold");
     52       bold.addActionListener(listener);
     53 
     54       italic = new JCheckBox("Italic");
     55       italic.addActionListener(listener);
     56 
     57       sample = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
     58       sample.setText("The quick brown fox jumps over the lazy dog");
     59       sample.setEditable(false);
     60       sample.setLineWrap(true);
     61       sample.setBorder(BorderFactory.createEtchedBorder());
     62 
     63       pane = new JScrollPane(sample);
     64 
     65       GroupLayout layout = new GroupLayout(getContentPane());
     66       setLayout(layout);
     67       layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
     68             .addGroup(
     69                   layout.createSequentialGroup().addContainerGap().addGroup(
     70                         layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
     71                               GroupLayout.Alignment.TRAILING,
     72                               layout.createSequentialGroup().addGroup(
     73                                     layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
     74                                           .addComponent(faceLabel).addComponent(sizeLabel))
     75                                     .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
     76                                     .addGroup(
     77                                           layout.createParallelGroup(
     78                                                 GroupLayout.Alignment.LEADING, false)
     79                                                 .addComponent(size).addComponent(face)))
     80                               .addComponent(italic).addComponent(bold)).addPreferredGap(
     81                         LayoutStyle.ComponentPlacement.RELATED).addComponent(pane)
     82                         .addContainerGap()));
     83 
     84       layout.linkSize(SwingConstants.HORIZONTAL, new java.awt.Component[] { face, size });
     85 
     86       layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
     87             .addGroup(
     88                   layout.createSequentialGroup().addContainerGap().addGroup(
     89                         layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(
     90                               pane, GroupLayout.Alignment.TRAILING).addGroup(
     91                               layout.createSequentialGroup().addGroup(
     92                                     layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
     93                                           .addComponent(face).addComponent(faceLabel))
     94                                     .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
     95                                     .addGroup(
     96                                           layout.createParallelGroup(
     97                                                 GroupLayout.Alignment.BASELINE).addComponent(size)
     98                                                 .addComponent(sizeLabel)).addPreferredGap(
     99                                           LayoutStyle.ComponentPlacement.RELATED).addComponent(
    100                                           italic, GroupLayout.DEFAULT_SIZE,
    101                                           GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    102                                     .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
    103                                     .addComponent(bold, GroupLayout.DEFAULT_SIZE,
    104                                           GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
    105                         .addContainerGap()));
    106       pack();
    107    }
    108    
    109    public void updateSample()
    110    {
    111       String fontFace = (String) face.getSelectedItem();
    112       int fontStyle = (bold.isSelected() ? Font.BOLD : 0)
    113             + (italic.isSelected() ? Font.ITALIC : 0);
    114       int fontSize = size.getItemAt(size.getSelectedIndex());
    115       Font font = new Font(fontFace, fontStyle, fontSize);
    116       sample.setFont(font);
    117       sample.repaint();
    118    }
    119 }
    
    

    测试程序11

    在elipse IDE中调试运行教材539页程序12-13、12-14,结合运行结果理解程序;

    掌握定制布局管理器的用法。

    记录示例代码阅读理解中存在的问题与疑惑。

    1 package circleLayout;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.33 2015-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class CircleLayoutTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          JFrame frame = new CircleLayoutFrame();
    16          frame.setTitle("CircleLayoutTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
     1 package circleLayout;
     2 
     3 import javax.swing.*;
     4 
     5 /**
     6  * A frame that shows buttons arranged along a circle.
     7  */
     8 public class CircleLayoutFrame extends JFrame
     9 {
    10    public CircleLayoutFrame()
    11    {
    12       setLayout(new CircleLayout());
    13       add(new JButton("Yellow"));
    14       add(new JButton("Blue"));
    15       add(new JButton("Red"));
    16       add(new JButton("Green"));
    17       add(new JButton("Orange"));
    18       add(new JButton("Fuchsia"));
    19       add(new JButton("Indigo"));
    20       pack();
    21    }
    22 }
    复制代码
    复制代码
      1 package circleLayout;
      2 
      3 import java.awt.*;
      4 
      5 /**
      6  * A layout manager that lays out components along a circle.
      7  */
      8 public class CircleLayout implements LayoutManager
      9 {
     10    private int minWidth = 0;
     11    private int minHeight = 0;
     12    private int preferredWidth = 0;
     13    private int preferredHeight = 0;
     14    private boolean sizesSet = false;
     15    private int maxComponentWidth = 0;
     16    private int maxComponentHeight = 0;
     17 
     18    public void addLayoutComponent(String name, Component comp)
     19    {
     20    }
     21 
     22    public void removeLayoutComponent(Component comp)
     23    {
     24    }
     25 
     26    public void setSizes(Container parent)
     27    {
     28       if (sizesSet) return;
     29       int n = parent.getComponentCount();
     30 
     31       preferredWidth = 0;
     32       preferredHeight = 0;
     33       minWidth = 0;
     34       minHeight = 0;
     35       maxComponentWidth = 0;
     36       maxComponentHeight = 0;
     37 
     38       // compute the maximum component widths and heights
     39       // and set the preferred size to the sum of the component sizes.
     40       for (int i = 0; i < n; i++)
     41       {
     42          Component c = parent.getComponent(i);
     43          if (c.isVisible())
     44          {
     45             Dimension d = c.getPreferredSize();
     46             maxComponentWidth = Math.max(maxComponentWidth, d.width);
     47             maxComponentHeight = Math.max(maxComponentHeight, d.height);
     48             preferredWidth += d.width;
     49             preferredHeight += d.height;
     50          }
     51       }
     52       minWidth = preferredWidth / 2;
     53       minHeight = preferredHeight / 2;
     54       sizesSet = true;
     55    }
     56 
     57    public Dimension preferredLayoutSize(Container parent)
     58    {
     59       setSizes(parent);
     60       Insets insets = parent.getInsets();
     61       int width = preferredWidth + insets.left + insets.right;
     62       int height = preferredHeight + insets.top + insets.bottom;
     63       return new Dimension(width, height);
     64    }
     65 
     66    public Dimension minimumLayoutSize(Container parent)
     67    {
     68       setSizes(parent);
     69       Insets insets = parent.getInsets();
     70       int width = minWidth + insets.left + insets.right;
     71       int height = minHeight + insets.top + insets.bottom;
     72       return new Dimension(width, height);
     73    }
     74 
     75    public void layoutContainer(Container parent)
     76    {
     77       setSizes(parent);
     78 
     79       // compute center of the circle
     80 
     81       Insets insets = parent.getInsets();
     82       int containerWidth = parent.getSize().width - insets.left - insets.right;
     83       int containerHeight = parent.getSize().height - insets.top - insets.bottom;
     84 
     85       int xcenter = insets.left + containerWidth / 2;
     86       int ycenter = insets.top + containerHeight / 2;
     87 
     88       // compute radius of the circle
     89 
     90       int xradius = (containerWidth - maxComponentWidth) / 2;
     91       int yradius = (containerHeight - maxComponentHeight) / 2;
     92       int radius = Math.min(xradius, yradius);
     93 
     94       // lay out components along the circle
     95 
     96       int n = parent.getComponentCount();
     97       for (int i = 0; i < n; i++)
     98       {
     99          Component c = parent.getComponent(i);
    100          if (c.isVisible())
    101          {
    102             double angle = 2 * Math.PI * i / n;
    103 
    104             // center point of component
    105             int x = xcenter + (int) (Math.cos(angle) * radius);
    106             int y = ycenter + (int) (Math.sin(angle) * radius);
    107 
    108             // move component so that its center is (x, y)
    109             // and its size is its preferred size
    110             Dimension d = c.getPreferredSize();
    111             c.setBounds(x - d.width / 2, y - d.height / 2, d.width, d.height);
    112          }
    113       }
    114    }
    115 }


    测试程序12

    在elipse IDE中调试运行教材544页程序12-15、12-16,结合运行结果理解程序;

    掌握选项对话框的用法。

    记录示例代码阅读理解中存在的问题与疑惑。

    1 package optionDialog;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.34 2015-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class OptionDialogTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          JFrame frame = new OptionDialogFrame();
    16          frame.setTitle("OptionDialogTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
     1 package optionDialog;
     2 
     3 import javax.swing.*;
     4 
     5 /**
     6  * A panel with radio buttons inside a titled border.
     7  */
     8 public class ButtonPanel extends JPanel
     9 {
    10    private ButtonGroup group;
    11 
    12    /**
    13     * Constructs a button panel.
    14     * @param title the title shown in the border
    15     * @param options an array of radio button labels
    16     */
    17    public ButtonPanel(String title, String... options)
    18    {
    19       setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
    20       setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    21       group = new ButtonGroup();
    22 
    23       // make one radio button for each option
    24       for (String option : options)
    25       {
    26          JRadioButton b = new JRadioButton(option);
    27          b.setActionCommand(option);
    28          add(b);
    29          group.add(b);
    30          b.setSelected(option == options[0]);
    31       }
    32    }
    33 
    34    /**
    35     * Gets the currently selected option.
    36     * @return the label of the currently selected radio button.
    37     */
    38    public String getSelection()
    39    {
    40       return group.getSelection().getActionCommand();
    41    }
    42 }
    复制代码
    复制代码
      1 package optionDialog;
      2 
      3 import java.awt.*;
      4 import java.awt.event.*;
      5 import java.awt.geom.*;
      6 import java.util.*;
      7 import javax.swing.*;
      8 
      9 /**
     10  * A frame that contains settings for selecting various option dialogs.
     11  */
     12 public class OptionDialogFrame extends JFrame
     13 {
     14    private ButtonPanel typePanel;
     15    private ButtonPanel messagePanel;
     16    private ButtonPanel messageTypePanel;
     17    private ButtonPanel optionTypePanel;
     18    private ButtonPanel optionsPanel;
     19    private ButtonPanel inputPanel;
     20    private String messageString = "Message";
     21    private Icon messageIcon = new ImageIcon("blue-ball.gif");
     22    private Object messageObject = new Date();
     23    private Component messageComponent = new SampleComponent();
     24 
     25    public OptionDialogFrame()
     26    {
     27       JPanel gridPanel = new JPanel();
     28       gridPanel.setLayout(new GridLayout(2, 3));
     29 
     30       typePanel = new ButtonPanel("Type", "Message", "Confirm", "Option", "Input");
     31       messageTypePanel = new ButtonPanel("Message Type", "ERROR_MESSAGE", "INFORMATION_MESSAGE",
     32             "WARNING_MESSAGE", "QUESTION_MESSAGE", "PLAIN_MESSAGE");
     33       messagePanel = new ButtonPanel("Message", "String", "Icon", "Component", "Other", 
     34             "Object[]");
     35       optionTypePanel = new ButtonPanel("Confirm", "DEFAULT_OPTION", "YES_NO_OPTION",
     36             "YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION");
     37       optionsPanel = new ButtonPanel("Option", "String[]", "Icon[]", "Object[]");
     38       inputPanel = new ButtonPanel("Input", "Text field", "Combo box");
     39 
     40       gridPanel.add(typePanel);
     41       gridPanel.add(messageTypePanel);
     42       gridPanel.add(messagePanel);
     43       gridPanel.add(optionTypePanel);
     44       gridPanel.add(optionsPanel);
     45       gridPanel.add(inputPanel);
     46 
     47       // add a panel with a Show button
     48 
     49       JPanel showPanel = new JPanel();
     50       JButton showButton = new JButton("Show");
     51       showButton.addActionListener(new ShowAction());
     52       showPanel.add(showButton);
     53 
     54       add(gridPanel, BorderLayout.CENTER);
     55       add(showPanel, BorderLayout.SOUTH);
     56       pack();
     57    }
     58 
     59    /**
     60     * Gets the currently selected message.
     61     * @return a string, icon, component, or object array, depending on the Message panel selection
     62     */
     63    public Object getMessage()
     64    {
     65       String s = messagePanel.getSelection();
     66       if (s.equals("String")) return messageString;
     67       else if (s.equals("Icon")) return messageIcon;
     68       else if (s.equals("Component")) return messageComponent;
     69       else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
     70             messageComponent, messageObject };
     71       else if (s.equals("Other")) return messageObject;
     72       else return null;
     73    }
     74 
     75    /**
     76     * Gets the currently selected options.
     77     * @return an array of strings, icons, or objects, depending on the Option panel selection
     78     */
     79    public Object[] getOptions()
     80    {
     81       String s = optionsPanel.getSelection();
     82       if (s.equals("String[]")) return new String[] { "Yellow", "Blue", "Red" };
     83       else if (s.equals("Icon[]")) return new Icon[] { new ImageIcon("yellow-ball.gif"),
     84             new ImageIcon("blue-ball.gif"), new ImageIcon("red-ball.gif") };
     85       else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
     86             messageComponent, messageObject };
     87       else return null;
     88    }
     89 
     90    /**
     91     * Gets the selected message or option type
     92     * @param panel the Message Type or Confirm panel
     93     * @return the selected XXX_MESSAGE or XXX_OPTION constant from the JOptionPane class
     94     */
     95    public int getType(ButtonPanel panel)
     96    {
     97       String s = panel.getSelection();
     98       try
     99       {
    100          return JOptionPane.class.getField(s).getInt(null);
    101       }
    102       catch (Exception e)
    103       {
    104          return -1;
    105       }
    106    }
    107 
    108    /**
    109     * The action listener for the Show button shows a Confirm, Input, Message, or Option dialog
    110     * depending on the Type panel selection.
    111     */
    112    private class ShowAction implements ActionListener
    113    {
    114       public void actionPerformed(ActionEvent event)
    115       {
    116          if (typePanel.getSelection().equals("Confirm")) JOptionPane.showConfirmDialog(
    117                OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
    118                getType(messageTypePanel));
    119          else if (typePanel.getSelection().equals("Input"))
    120          {
    121             if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog(
    122                   OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
    123             else JOptionPane.showInputDialog(OptionDialogFrame.this, getMessage(), "Title",
    124                   getType(messageTypePanel), null, new String[] { "Yellow", "Blue", "Red" },
    125                   "Blue");
    126          }
    127          else if (typePanel.getSelection().equals("Message")) JOptionPane.showMessageDialog(
    128                OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
    129          else if (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog(
    130                OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
    131                getType(messageTypePanel), null, getOptions(), getOptions()[0]);
    132       }
    133    }
    134 }
    135 
    136 /**
    137  * A component with a painted surface
    138  */
    139 
    140 class SampleComponent extends JComponent
    141 {
    142    public void paintComponent(Graphics g)
    143    {
    144       Graphics2D g2 = (Graphics2D) g;
    145       Rectangle2D rect = new Rectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1);
    146       g2.setPaint(Color.YELLOW);
    147       g2.fill(rect);
    148       g2.setPaint(Color.BLUE);
    149       g2.draw(rect);
    150    }
    151 
    152    public Dimension getPreferredSize()
    153    {
    154       return new Dimension(10, 10);
    155    }
    156 }
    
    

    测试程序13

    在elipse IDE中调试运行教材552页程序12-17、12-18,结合运行结果理解程序;

    掌握对话框的创建方法;

    记录示例代码阅读理解中存在的问题与疑惑。

     1 package dialog;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.34 2012-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class DialogTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          JFrame frame = new DialogFrame();
    16          frame.setTitle("DialogTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
     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);

          // Construct a File menu.

          JMenuBar menuBar = new JMenuBar();//菜单栏的实现
          setJMenuBar(menuBar);//设置此窗体的菜单栏
          JMenu fileMenu = new JMenu("File");//菜单的该实现是一个包含 JMenuItem 的弹出窗口,用户选择 JMenuBar 上的项时会显示该 JMenuItem。
          menuBar.add(fileMenu);//将指定的菜单追加到菜单栏的末尾

          // Add About and Exit menu items.

          // The About item shows the About dialog.

          JMenuItem aboutItem = new JMenuItem("About");//菜单中的项的实现
          aboutItem.addActionListener(event -> {
             if (dialog == null) // first time
                dialog = new AboutDialog(DialogFrame.this);
             dialog.setVisible(true); // 设置是否可见
          });
          fileMenu.add(aboutItem);//将某个菜单项追加到此菜单的末尾。返回添加的菜单项

          // The Exit item exits the program.

          JMenuItem exitItem = new JMenuItem("Exit");
          exitItem.addActionListener(event -> System.exit(0));
          fileMenu.add(exitItem);
       }
    复制代码
    复制代码
     1 package dialog;
     2 
     3 import java.awt.BorderLayout;
     4 
     5 import javax.swing.JButton;
     6 import javax.swing.JDialog;
     7 import javax.swing.JFrame;
     8 import javax.swing.JLabel;
     9 import javax.swing.JPanel;
    10 
    11 /**
    12  * A sample modal dialog that displays a message and waits for the user to click the OK button.
    13  */
    14 public class AboutDialog extends JDialog
    15 {//创建一个具有指定标题,所有者Farmer和模式的对话框。如果owner为null,则一个共享的,隐藏的窗体将设置为该对话框的所有者。
    16    public AboutDialog(JFrame owner)
    17    {
    18       super(owner, "About DialogTest", true);
    19 
    20       // add HTML label to center//将指定的组件添加到此内容的尾部
    21 
    22       add(
    23             new JLabel(
    24                   "<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"),
    25             BorderLayout.CENTER);
    26 
    27       // OK button closes the dialog
    28 
    29       JButton ok = new JButton("OK");//创建一个新的按钮
    30       ok.addActionListener(event -> setVisible(false));
    31 
    32       // add OK button to southern border
    33 
    34       JPanel panel = new JPanel();
    35       panel.add(ok);
    36       add(panel, BorderLayout.SOUTH);//边框布局,显示在下边
    37 
    38       pack();
    39    }
    40 }

    
    

    测试程序14

    在elipse IDE中调试运行教材556页程序12-19、12-20,结合运行结果理解程序;

    掌握对话框的数据交换用法;

    记录示例代码阅读理解中存在的问题与疑惑。

     1 package dataExchange;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.34 2015-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class DataExchangeTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          JFrame frame = new DataExchangeFrame();
    16          frame.setTitle("DataExchangeTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
     1 package dataExchange;
     2 
     3 import java.awt.*;
     4 import java.awt.event.*;
     5 import javax.swing.*;
     6 
     7 /**
     8  * A frame with a menu whose File->Connect action shows a password dialog.
     9  */
    10 public class DataExchangeFrame extends JFrame
    11 {
    12    public static final int TEXT_ROWS = 20;
    13    public static final int TEXT_COLUMNS = 40;
    14    private PasswordChooser dialog = null;
    15    private JTextArea textArea;
    16 
    17    public DataExchangeFrame()
    18    {
    19       // construct a File menu
    20 
    21       JMenuBar mbar = new JMenuBar();
    22       setJMenuBar(mbar);
    23       JMenu fileMenu = new JMenu("File");
    24       mbar.add(fileMenu);
    25 
    26       // add Connect and Exit menu items
    27 
    28       JMenuItem connectItem = new JMenuItem("Connect");
    29       connectItem.addActionListener(new ConnectAction());
    30       fileMenu.add(connectItem);
    31 
    32       // The Exit item exits the program
    33 
    34       JMenuItem exitItem = new JMenuItem("Exit");
    35       exitItem.addActionListener(event -> System.exit(0));
    36       fileMenu.add(exitItem);
    37 
    38       textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
    39       add(new JScrollPane(textArea), BorderLayout.CENTER);
    40       pack();
    41    }
    42 
    43    /**
    44     * The Connect action pops up the password dialog.
    45     */
    46    private class ConnectAction implements ActionListener
    47    {
    48       public void actionPerformed(ActionEvent event)
    49       {
    50          // if first time, construct dialog
    51 
    52          if (dialog == null) dialog = new PasswordChooser();
    53 
    54          // set default values
    55          dialog.setUser(new User("yourname", null));
    56 
    57          // pop up dialog
    58          if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
    59          {
    60             // if accepted, retrieve user input
    61             User u = dialog.getUser();
    62             textArea.append("user name = " + u.getName() + ", password = "
    63                   + (new String(u.getPassword())) + "
    ");
    64          }
    65       }
    66    }
    67 }
    复制代码
    复制代码
      1 package dataExchange;
      2 
      3 import java.awt.BorderLayout;
      4 import java.awt.Component;
      5 import java.awt.Frame;
      6 import java.awt.GridLayout;
      7 
      8 import javax.swing.JButton;
      9 import javax.swing.JDialog;
     10 import javax.swing.JLabel;
     11 import javax.swing.JPanel;
     12 import javax.swing.JPasswordField;
     13 import javax.swing.JTextField;
     14 import javax.swing.SwingUtilities;
     15 
     16 /**
     17  * A password chooser that is shown inside a dialog
     18  */
     19 public class PasswordChooser extends JPanel
     20 {
     21    private JTextField username;
     22    private JPasswordField password;
     23    private JButton okButton;
     24    private boolean ok;
     25    private JDialog dialog;
     26 
     27    public PasswordChooser()
     28    {
     29       setLayout(new BorderLayout());
     30 
     31       // construct a panel with user name and password fields
     32 
     33       JPanel panel = new JPanel();
     34       panel.setLayout(new GridLayout(2, 2));
     35       panel.add(new JLabel("User name:"));
     36       panel.add(username = new JTextField(""));
     37       panel.add(new JLabel("Password:"));
     38       panel.add(password = new JPasswordField(""));
     39       add(panel, BorderLayout.CENTER);
     40 
     41       // create Ok and Cancel buttons that terminate the dialog
     42 
     43       okButton = new JButton("Ok");
     44       okButton.addActionListener(event -> {
     45          ok = true;
     46          dialog.setVisible(false);
     47       });
     48 
     49       JButton cancelButton = new JButton("Cancel");
     50       cancelButton.addActionListener(event -> dialog.setVisible(false));
     51 
     52       // add buttons to southern border
     53 
     54       JPanel buttonPanel = new JPanel();
     55       buttonPanel.add(okButton);
     56       buttonPanel.add(cancelButton);
     57       add(buttonPanel, BorderLayout.SOUTH);
     58    }
     59 
     60    /**
     61     * Sets the dialog defaults.
     62     * @param u the default user information
     63     */
     64    public void setUser(User u)
     65    {
     66       username.setText(u.getName());
     67    }
     68 
     69    /**
     70     * Gets the dialog entries.
     71     * @return a User object whose state represents the dialog entries
     72     */
     73    public User getUser()
     74    {
     75       return new User(username.getText(), password.getPassword());
     76    }
     77 
     78    /**
     79     * Show the chooser panel in a dialog
     80     * @param parent a component in the owner frame or null
     81     * @param title the dialog window title
     82     */
     83    public boolean showDialog(Component parent, String title)
     84    {
     85       ok = false;
     86 
     87       // locate the owner frame
     88 
     89       Frame owner = null;
     90       if (parent instanceof Frame)
     91          owner = (Frame) parent;
     92       else
     93          owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
     94 
     95       // if first time, or if owner has changed, make new dialog
     96 
     97       if (dialog == null || dialog.getOwner() != owner)
     98       {
     99          dialog = new JDialog(owner, true);
    100          dialog.add(this);
    101          dialog.getRootPane().setDefaultButton(okButton);
    102          dialog.pack();
    103       }
    104 
    105       // set title and show dialog
    106 
    107       dialog.setTitle(title);
    108       dialog.setVisible(true);
    109       return ok;
    110    }
    111 }
    复制代码
    复制代码
     1 package dataExchange;
     2 
     3 /**
     4  * A user has a name and password. For security reasons, the password is stored as a char[], not a
     5  * String.
     6  */
     7 public class User
     8 {
     9    private String name;
    10    private char[] password;
    11 
    12    public User(String aName, char[] aPassword)
    13    {
    14       name = aName;
    15       password = aPassword;
    16    }
    17 
    18    public String getName()
    19    {
    20       return name;
    21    }
    22 
    23    public char[] getPassword()
    24    {
    25       return password;
    26    }
    27 
    28    public void setName(String aName)
    29    {
    30       name = aName;
    31    }
    32 
    33    public void setPassword(char[] aPassword)
    34    {
    35       password = aPassword;
    36    }
    37 }
    
    

    测试程序15

    在elipse IDE中调试运行教材556页程序12-21、12-2212-23,结合程序运行结果理解程序;

    掌握文件对话框的用法;

    记录示例代码阅读理解中存在的问题与疑惑。

     

      

    package fileChooser;
    
    import java.io.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import javax.swing.filechooser.FileFilter;
    
    /**
     * A file view that displays an icon for all files that match a file filter.
     */
    public class FileIconView extends FileView {
        private FileFilter filter;
        private Icon icon;
    
        /**
         * Constructs a FileIconView.
         * 
         * @param aFilter a file filter--all files that this filter accepts will be
         *                shown with the icon.
         * @param         anIcon--the icon shown with all accepted files.
         */
        public FileIconView(FileFilter aFilter, Icon anIcon) {
            filter = aFilter;
            icon = anIcon;
        }
    
        public Icon getIcon(File f) {
            if (!f.isDirectory() && filter.accept(f))
                return icon;
            else
                return null;
        }
    }

    package fileChooser;
    
    import java.awt.*;
    import java.io.*;
    
    import javax.swing.*;
    
    /**
     * A file chooser accessory that previews images.
     */
    public class ImagePreviewer extends JLabel {
        /**
         * Constructs an ImagePreviewer.
         * 
         * @param chooser the file chooser whose property changes trigger an image
         *                change in this previewer
         */
        public ImagePreviewer(JFileChooser chooser) {
            setPreferredSize(new Dimension(100, 100));
            setBorder(BorderFactory.createEtchedBorder());
    
            chooser.addPropertyChangeListener(event -> {
                if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) {
                    // the user has selected a new file
                    File f = (File) event.getNewValue();
                    if (f == null) {
                        setIcon(null);
                        return;
                    }
    
                    // read the image into an icon
                    ImageIcon icon = new ImageIcon(f.getPath());
    
                    // if the icon is too large to fit, scale it
                    if (icon.getIconWidth() > getWidth())
                        icon = new ImageIcon(icon.getImage().getScaledInstance(getWidth(), -1, Image.SCALE_DEFAULT));
    
                    setIcon(icon);
                }
            });
        }
    }
    package fileChooser;
    
    import java.io.*;
    
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import javax.swing.filechooser.FileFilter;
    
    /**
     * A frame that has a menu for loading an image and a display area for the
     * loaded image.
     */
    public class ImageViewerFrame extends JFrame {
        private static final int DEFAULT_WIDTH = 300;
        private static final int DEFAULT_HEIGHT = 400;
        private JLabel label;
        private JFileChooser chooser;
    
        public ImageViewerFrame() {
            setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    
            // set up menu bar
            JMenuBar menuBar = new JMenuBar();
            setJMenuBar(menuBar);
    
            JMenu menu = new JMenu("File");
            menuBar.add(menu);
    
            JMenuItem openItem = new JMenuItem("Open");
            menu.add(openItem);
            openItem.addActionListener(event -> {
                chooser.setCurrentDirectory(new File("."));
    
                // show file chooser dialog
                int result = chooser.showOpenDialog(ImageViewerFrame.this);
    
                // if image file accepted, set it as icon of the label
                if (result == JFileChooser.APPROVE_OPTION) {
                    String name = chooser.getSelectedFile().getPath();
                    label.setIcon(new ImageIcon(name));
                    pack();
                }
            });
    
            JMenuItem exitItem = new JMenuItem("Exit");
            menu.add(exitItem);
            exitItem.addActionListener(event -> System.exit(0));
    
            // use a label to display the images
            label = new JLabel();
            add(label);
    
            // set up file chooser
            chooser = new JFileChooser();
    
            // accept all image files ending with .jpg, .jpeg, .gif
            FileFilter filter = new FileNameExtensionFilter("Image files", "jpg", "jpeg", "gif");
            chooser.setFileFilter(filter);
    
            chooser.setAccessory(new ImagePreviewer(chooser));
    
            chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif")));
        }
    }

    
    
     

      

     

      

     

    测试程序16

    在elipse IDE中调试运行教材570页程序12-24,结合运行结果理解程序;

    了解颜色选择器的用法。

    记录示例代码阅读理解中存在的问题与疑惑。

     1 package colorChooser;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 /**
     7  * @version 1.04 2015-06-12
     8  * @author Cay Horstmann
     9  */
    10 public class ColorChooserTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       EventQueue.invokeLater(() -> {
    15          JFrame frame = new ColorChooserFrame();
    16          frame.setTitle("ColorChooserTest");
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
    复制代码
    复制代码
     1 package colorChooser;
     2 
     3 import java.awt.Color;
     4 import java.awt.Frame;
     5 import java.awt.event.ActionEvent;
     6 import java.awt.event.ActionListener;
     7 
     8 import javax.swing.JButton;
     9 import javax.swing.JColorChooser;
    10 import javax.swing.JDialog;
    11 import javax.swing.JPanel;
    12 
    13 /**
    14  * A panel with buttons to pop up three types of color choosers
    15  */
    16 public class ColorChooserPanel extends JPanel
    17 {
    18    public ColorChooserPanel()
    19    {
    20       JButton modalButton = new JButton("Modal");
    21       modalButton.addActionListener(new ModalListener());
    22       add(modalButton);
    23 
    24       JButton modelessButton = new JButton("Modeless");
    25       modelessButton.addActionListener(new ModelessListener());
    26       add(modelessButton);
    27 
    28       JButton immediateButton = new JButton("Immediate");
    29       immediateButton.addActionListener(new ImmediateListener());
    30       add(immediateButton);
    31    }
    32 
    33    /**
    34     * This listener pops up a modal color chooser
    35     */
    36    private class ModalListener implements ActionListener
    37    {
    38       public void actionPerformed(ActionEvent event)
    39       {
    40          Color defaultColor = getBackground();
    41          Color selected = JColorChooser.showDialog(ColorChooserPanel.this, "Set background",
    42                defaultColor);
    43          if (selected != null) setBackground(selected);
    44       }
    45    }
    46 
    47    /**
    48     * This listener pops up a modeless color chooser. The panel color is changed when the user
    49     * clicks the OK button.
    50     */
    51    private class ModelessListener implements ActionListener
    52    {
    53       private JDialog dialog;
    54       private JColorChooser chooser;
    55 
    56       public ModelessListener()
    57       {
    58          chooser = new JColorChooser();
    59          dialog = JColorChooser.createDialog(ColorChooserPanel.this, "Background Color",
    60                false /* not modal */, chooser, 
    61                event -> setBackground(chooser.getColor()), 
    62                null /* no Cancel button listener */);
    63       }
    64 
    65       public void actionPerformed(ActionEvent event)
    66       {
    67          chooser.setColor(getBackground());
    68          dialog.setVisible(true);
    69       }
    70    }
    71 
    72    /**
    73     * This listener pops up a modeless color chooser. The panel color is changed immediately when
    74     * the user picks a new color.
    75     */
    76    private class ImmediateListener implements ActionListener
    77    {
    78       private JDialog dialog;
    79       private JColorChooser chooser;
    80 
    81       public ImmediateListener()
    82       {
    83          chooser = new JColorChooser();
    84          chooser.getSelectionModel().addChangeListener(
    85                event -> setBackground(chooser.getColor()));
    86 
    87          dialog = new JDialog((Frame) null, false /* not modal */);
    88          dialog.add(chooser);
    89          dialog.pack();
    90       }
    91 
    92       public void actionPerformed(ActionEvent event)
    93       {
    94          chooser.setColor(getBackground());
    95          dialog.setVisible(true);
    96       }
    97    }
    98 }
    复制代码
    复制代码
     1 package colorChooser;
     2 
     3 import javax.swing.*;
     4 
     5 /**
     6  * A frame with a color chooser panel
     7  */
     8 public class ColorChooserFrame extends JFrame
     9 {
    10    private static final int DEFAULT_WIDTH = 300;
    11    private static final int DEFAULT_HEIGHT = 200;
    12 
    13    public ColorChooserFrame()
    14    {      
    15       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    16 
    17       // add color chooser panel to frame
    18 
    19       ColorChooserPanel panel = new ColorChooserPanel();
    20       add(panel);
    21    }
    22 }
    
    

    实验2:组内讨论反思本组负责程序,理解程序总体结构,梳理程序GUI设计中应用的相关组件,整理相关组件的API,对程序中组件应用的相关代码添加注释。

    实验3:组间协同学习:在本班课程QQ群内,各位同学对实验1中存在的问题进行提问,提问时注明实验1中的测试程序编号,负责对应程序的小组需及时对群内提问进行回答。

    实验总结:这次主要负责的测试程序13在这个实验中12-17是测试程序框架类的代码,12-18是显示了对话框类。在实验中要实现一个对话框,需要从JDialong派生一个类。

    在对话框构造器中,调用超类JDialong的构造器;添加用户框的用户界面组件;添加事件处理器;设置对话框的大小.。

    在例子中添加的是标签和按钮,并且为按钮设置了处理器,还设置了对话框的大小。

    拥有这框架控制对话框的显示位置,如果将拥有者标识为null,那么对话框将由一个隐藏框架所拥有。

    在这个实验本来弄得时候就只有空的一个框架,后来在进行重新的导入就有了现在的对话框,在这次代码中只建立一次对话框,无论何时用户点击About按钮,都可以重复使用。

  • 相关阅读:
    linux系统——Redis集群搭建(主从+哨兵模式)
    java线程池的使用(jdk1.8)
    JVM内存参数配置
    idea maven 打包过程(没有主属性清单)
    如何让脚本在任意地方可执行 咔咔
    终结初学者对ElasticSearch、Kibana、Logstash安装的种种困难 咔咔
    免费增加几个T电脑空间方法,拿去不谢 咔咔
    聊聊MySQL的加锁规则《死磕MySQL系列 十五》 咔咔
    为什么不让用join?《死磕MySQL系列 十六》 咔咔
    时光卷轴,到2025年,数字经济核心产业增加值将达到13.8万亿元,如何看清数字产业,抓住这个风口
  • 原文地址:https://www.cnblogs.com/qiongji/p/10053637.html
Copyright © 2020-2023  润新知