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界面中事件处理技术的用途。

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

  1. package calculator;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6.  
  7. /**
  8. * A panel with calculator buttons and a result display.
  9. */
  10. public class CalculatorPanel extends JPanel
  11. {
  12. //定义了五个对象
  13. private JButton display;
  14. private JPanel panel;
  15. private double result;
  16. private String lastCommand;
  17. private boolean start;
  18.  
  19. public CalculatorPanel()
  20. {
  21. setLayout(new BorderLayout());
  22.  
  23. result = 0;
  24. lastCommand = "=";
  25. start = true;
  26.  
  27. // add the display
  28.  
  29. display = new JButton("0");// display用来显示一个算法的结果
  30. display.setEnabled(false);
  31. add(display, BorderLayout.NORTH);
  32. //定义了两个监听器对象
  33. ActionListener insert = new InsertAction();
  34. ActionListener command = new CommandAction();
  35.  
  36. // add the buttons in a 4 x 4 grid
  37.  
  38. panel = new JPanel();//容器组件
  39. panel.setLayout(new GridLayout(4, 4));//四行四列的网格
  40. //调用addButton方法来添加按钮
  41. addButton("3", insert);
  42. addButton("6", insert);
  43. addButton("9", insert);
  44. addButton("/", command);
  45.  
  46. addButton("2", insert);
  47. addButton("5", insert);
  48. addButton("8", insert);
  49. addButton("*", command);
  50.  
  51. addButton("1", insert);
  52. addButton("4", insert);
  53. addButton("7", insert);
  54. addButton("-", command);
  55.  
  56. addButton("0", insert);
  57. addButton(".", insert);
  58. addButton("=", command);
  59. addButton("+", command);
  60. //创建了16个事件源
  61.  
  62. add(panel, BorderLayout.SOUTH);
  63. JButton b1= new JButton("验证");
  64. add(b1, BorderLayout.CENTER);
  65. }
  66.  
  67. /**
  68. * Adds a button to the center panel.
  69. * @param label the button label
  70. * @param listener the button listener
  71. */
  72. private void addButton(String label, ActionListener listener)
  73. {
  74. JButton button = new JButton(label);
  75. button.addActionListener(listener);
  76. panel.add(button);
  77. }
  78.  
  79. /**
  80. * This action inserts the button action string to the end of the display text.
  81. */
  82. private class InsertAction implements ActionListener
  83. {
  84. public void actionPerformed(ActionEvent event)
  85. {
  86. String input = event.getActionCommand();//通过事件源来获得动作
  87. if (start)
  88. {
  89. display.setText("");//用setText方法 来更改
  90. start = false;
  91. }
  92. display.setText(display.getText() + input);
  93. }
  94. }
  95.  
  96. /**
  97. * This action executes the command that the button action string denotes.
  98. */
  99. private class CommandAction implements ActionListener
  100. {
  101. public void actionPerformed(ActionEvent event)
  102. {
  103. String command = event.getActionCommand();
  104.  
  105. if (start)
  106. {
  107. if (command.equals("-"))
  108. {
  109. display.setText(command);
  110. start = false;
  111. }
  112. else lastCommand = command;
  113. }
  114. else
  115. {
  116. calculate(Double.parseDouble(display.getText()));
  117. //将数字字符串转换成对应的数字,用parseDouble
  118. lastCommand = command;//控制变量
  119. start = true;
  120. }
  121. }
  122. }
  123.  
  124. /**
  125. * Carries out the pending calculation.
  126. * @param x the value to be accumulated with the prior result.
  127. */
  128. public void calculate(double x)
  129. {
  130. if (lastCommand.equals("+")) result += x;
  131. else if (lastCommand.equals("-")) result -= x;
  132. else if (lastCommand.equals("*")) result *= x;
  133. else if (lastCommand.equals("/")) result /= x;
  134. else if (lastCommand.equals("=")) result = x;
  135. display.setText("" + result);//""的意义在于字符串的转换
  136. }
  137. }
  1. package calculator;
  2.  
  3. import javax.swing.*;
  4.  
  5. /**
  6. * A frame with a calculator panel.
  7. */
  8. public class CalculatorFrame extends JFrame
  9. {
  10. public CalculatorFrame()
  11. {
  12. add(new CalculatorPanel());
  13. pack();//用pack方法
  14. }
  15. }
  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. }

结果如下:

测试程序2

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

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

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

  1. package text;
  2.  
  3. import java.awt.BorderLayout;
  4. import java.awt.GridLayout;
  5.  
  6. import javax.swing.JButton;
  7. import javax.swing.JFrame;
  8. import javax.swing.JLabel;
  9. import javax.swing.JPanel;
  10. import javax.swing.JPasswordField;
  11. import javax.swing.JScrollPane;
  12. import javax.swing.JTextArea;
  13. import javax.swing.JTextField;
  14. import javax.swing.SwingConstants;
  15.  
  16. /**
  17. * A frame with sample text components.
  18. */
  19. public class TextComponentFrame extends JFrame
  20. { //定义网格的行数、列数
  21. public static final int TEXTAREA_ROWS = 8;
  22. public static final int TEXTAREA_COLUMNS = 20;
  23.  
  24. public TextComponentFrame()
  25. {
  26. JTextField textField = new JTextField();//创建一个新的文本域
  27. JPasswordField passwordField = new JPasswordField();
  28.  
  29. JPanel northPanel = new JPanel();//构造一个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);//add方法
  37.  
  38. JTextArea textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS);
  39. JScrollPane scrollPane = new JScrollPane(textArea);
  40.  
  41. add(scrollPane, BorderLayout.CENTER);
  42.  
  43. // add button to append text into the text area
  44.  
  45. JPanel southPanel = new JPanel();
  46.  
  47. JButton insertButton = new JButton("Insert");
  48. southPanel.add(insertButton);
  49. insertButton.addActionListener(event ->
  50. textArea.append("User name: " + textField.getText() + " Password: "
  51. + new String(passwordField.getPassword()) + "\n"));
  52.  
  53. add(southPanel, BorderLayout.SOUTH);
  54. pack();
  55. }
  56. }

Text

  1. package text;
  2.  
  3. import java.awt.*;
  4. import javax.swing.*;
  5.  
  6. /**
  7. * @version 1.41 2015-06-12
  8. * @author Cay Horstmann
  9. */
  10. public class TextComponentTest
  11. {
  12. public static void main(String[] args)
  13. {
  14. EventQueue.invokeLater(() -> {
  15. JFrame frame = new TextComponentFrame();//生成 TextComponentFrame类的GUI界面对象
  16. frame.setTitle("TextComponentTest");
  17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭界面的按钮操作
  18. frame.setVisible(true);//使结果可见的
  19. });
  20. }
  21. }

text

结果如下:

测试程序3

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

l 掌握复选框组件的用法;

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

  1. package checkBox;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6.  
  7. /**
  8. * A frame with a sample text label and check boxes for selecting font
  9. * attributes.
  10. */
  11. public class CheckBoxFrame extends JFrame
  12. { //定义四个私有属性
  13. private JLabel label;
  14. private JCheckBox bold;
  15. private JCheckBox italic;
  16. private static final int FONTSIZE = 24;
  17.  
  18. public CheckBoxFrame()
  19. {
  20. // add the sample text label
  21. //添加示例文本标签
  22.  
  23. label = new JLabel("The quick brown fox jumps over the lazy dog.");//创建新标签
  24. label.setFont(new Font("Serif", Font.BOLD, FONTSIZE));//设置字体
  25. add(label, BorderLayout.CENTER);
  26.  
  27. // this listener sets the font attribute of
  28. // the label to the check box state
  29.  
  30. ActionListener listener = event -> {
  31. int mode = 0;
  32. if (bold.isSelected()) mode += Font.BOLD;
  33. if (italic.isSelected()) mode += Font.ITALIC;
  34. label.setFont(new Font("Serif", mode, FONTSIZE));//设置面板中的字体
  35. };
  36.  
  37. // add the check boxes
  38.  
  39. JPanel buttonPanel = new JPanel();
  40.  
  41. bold = new JCheckBox("Bold");//在构造器中指定标签文本
  42. bold.addActionListener(listener);
  43. bold.setSelected(true);//返回每个复选框的当前状态
  44. buttonPanel.add(bold);
  45.  
  46. italic = new JCheckBox("Italic");
  47. italic.addActionListener(listener);
  48. buttonPanel.add(italic);
  49.  
  50. add(buttonPanel, BorderLayout.SOUTH);
  51. pack();//调整此窗口的大小
  52. }
  53. }
  54.  
  55. package checkBox;
  56.  
  57. import java.awt.*;
  58. import javax.swing.*;
  59.  
  60. /**
  61. * @version 1.34 2015-06-12
  62. * @author Cay Horstmann
  63. */
  64. public class CheckBoxTest
  65. {
  66. public static void main(String[] args)
  67. {
  68. EventQueue.invokeLater(() -> {
  69. JFrame frame = new CheckBoxFrame();
  70. frame.setTitle("CheckBoxTest");//设置Title为复选框
  71. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  72. frame.setVisible(true);
  73. });
  74. }
  75. }

CheckBoxTest

结果如下:

测试程序4

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

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

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

  1. package radioButton;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6.  
  7. /**
  8. * A frame with a sample text label and radio buttons for selecting font sizes.
  9. */
  10. public class RadioButtonFrame extends JFrame//单选按钮
  11. { //定义四个私有属性
  12. private JPanel buttonPanel;
  13. private ButtonGroup group;
  14. private JLabel label;
  15. private static final int DEFAULT_SIZE = 36;
  16.  
  17. public RadioButtonFrame()
  18. {
  19. // add the sample text label
  20.  
  21. label = new JLabel("The quick brown fox jumps over the lazy dog.");
  22. label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));//设置新字体
  23. add(label, BorderLayout.CENTER);
  24.  
  25. // add the radio buttons
  26.  
  27. buttonPanel = new JPanel();
  28. group = new ButtonGroup();
  29. //添加单选框按钮
  30. addRadioButton("Small", 8);
  31. addRadioButton("Medium", 12);
  32. addRadioButton("Large", 18);
  33. addRadioButton("Extra large", 36);
  34.  
  35. add(buttonPanel, BorderLayout.SOUTH);
  36. pack();//调整窗口的大小
  37. }
  38.  
  39. /**
  40. * Adds a radio button that sets the font size of the sample text.
  41. * @param name the string to appear on the button
  42. * @param size the font size that this button sets
  43. */
  44. public void addRadioButton(String name, int size)
  45. {
  46. boolean selected = size == DEFAULT_SIZE;//布尔类型,大小的定义
  47. JRadioButton button = new JRadioButton(name, selected);
  48. group.add(button);
  49. buttonPanel.add(button);
  50.  
  51. // this listener sets the label font size
  52. //这个监听器设置标签字体大小
  53.  
  54. ActionListener listener = event -> label.setFont(new Font("Serif", Font.PLAIN, size));//表明新的字体,大小
  55.  
  56. button.addActionListener(listener);
  57. }
  58. }

radioButton

结果如下:

测试程序5

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

l 掌握边框的用法;

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

  1. package border;
  2.  
  3. import java.awt.*;
  4. import javax.swing.*;
  5. import javax.swing.border.*;
  6.  
  7. /**
  8. * A frame with radio buttons to pick a border style.
  9. */
  10. public class BorderFrame extends JFrame
  11. {
  12. private JPanel demoPanel;
  13. private JPanel buttonPanel;
  14. private ButtonGroup group;
  15.  
  16. public BorderFrame()
  17. {
  18. demoPanel = new JPanel();
  19. buttonPanel = new JPanel();
  20. group = new ButtonGroup();
  21.  
  22. addRadioButton("Lowered bevel", BorderFactory.createLoweredBevelBorder());
  23. addRadioButton("Raised bevel", BorderFactory.createRaisedBevelBorder());
  24. addRadioButton("Etched", BorderFactory.createEtchedBorder());
  25. addRadioButton("Line", BorderFactory.createLineBorder(Color.BLUE));
  26. addRadioButton("Matte", BorderFactory.createMatteBorder(10, 10, 10, 10, Color.BLUE));
  27. addRadioButton("Empty", BorderFactory.createEmptyBorder());
  28.  
  29. Border etched = BorderFactory.createEtchedBorder();
  30. Border titled = BorderFactory.createTitledBorder(etched, "Border types");
  31. buttonPanel.setBorder(titled);
  32.  
  33. setLayout(new GridLayout(2, 1));
  34. add(buttonPanel);
  35. add(demoPanel);
  36. pack();
  37. }
  38.  
  39. public void addRadioButton(String buttonName, Border b)
  40. {
  41. JRadioButton button = new JRadioButton(buttonName);
  42. button.addActionListener(event -> demoPanel.setBorder(b));
  43. group.add(button);
  44. buttonPanel.add(button);
  45. }
  46. }
  47.  
  48. package border;
  49.  
  50. import java.awt.*;
  51. import javax.swing.*;
  52.  
  53. /**
  54. * @version 1.34 2015-06-13
  55. * @author Cay Horstmann
  56. */
  57. public class BorderTest
  58. {
  59. public static void main(String[] args)
  60. {
  61. EventQueue.invokeLater(() -> {
  62. JFrame frame = new BorderFrame();
  63. frame.setTitle("BorderTest");
  64. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  65. frame.setVisible(true);
  66. });
  67. }
  68. }

BorderFrame

测试程序6

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

l 掌握组合框组件的用法;

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

  1. package comboBox;
  2.  
  3. import java.awt.BorderLayout;
  4. import java.awt.Font;
  5.  
  6. import javax.swing.JComboBox;
  7. import javax.swing.JFrame;
  8. import javax.swing.JLabel;
  9. import javax.swing.JPanel;
  10.  
  11. /**
  12. * A frame with a sample text label and a combo box for selecting font faces.
  13. */
  14. public class ComboBoxFrame extends JFrame
  15. {
  16. private JComboBox<String> faceCombo;//定义组合框面
  17. private JLabel label;//定义标签
  18. private static final int DEFAULT_SIZE = 24;
  19.  
  20. public ComboBoxFrame()
  21. {
  22. // add the sample text label
  23.  
  24. label = new JLabel("The quick brown fox jumps over the lazy dog.");
  25. label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));//设置组件的字体
  26. add(label, BorderLayout.CENTER);
  27.  
  28. // make a combo box and add face names
  29. //调用addItem方法添加选项
  30. faceCombo = new JComboBox<>();
  31. faceCombo.addItem("Serif");
  32. faceCombo.addItem("SansSerif");
  33. faceCombo.addItem("Monospaced");
  34. faceCombo.addItem("Dialog");
  35. faceCombo.addItem("DialogInput");
  36.  
  37. // the combo box listener changes the label font to the selected face name
  38.  
  39. faceCombo.addActionListener(event ->//组合框产生一个动作事件
  40. label.setFont(
  41. new Font(faceCombo.getItemAt(faceCombo.getSelectedIndex()),
  42. Font.PLAIN, DEFAULT_SIZE)));
  43.  
  44. // add combo box to a panel at the frame's southern border
  45.  
  46. JPanel comboPanel = new JPanel();
  47. comboPanel.add(faceCombo);
  48. add(comboPanel, BorderLayout.SOUTH);
  49. pack();
  50. }
  51. }

comboBox

测试程序7

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

l 掌握滑动条组件的用法;

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

  1. package slider;
  2.  
  3. import java.awt.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6. import javax.swing.event.*;
  7.  
  8. /**
  9. * A frame with many sliders and a text field to show slider values.
  10. */
  11. public class SliderFrame extends JFrame
  12. {
  13. private JPanel sliderPanel;
  14. private JTextField textField;
  15. private ChangeListener listener;
  16.  
  17. public SliderFrame()
  18. {
  19. sliderPanel = new JPanel();
  20. sliderPanel.setLayout(new GridBagLayout());
  21.  
  22. // common listener for all sliders
  23. listener = event -> {
  24. // update text field when the slider value changes
  25. JSlider source = (JSlider) event.getSource();
  26. textField.setText("" + source.getValue());
  27. };
  28.  
  29. // add a plain slider
  30. //添加一个普通滑块
  31.  
  32. JSlider slider = new JSlider();//构造一个滑动条
  33. addSlider(slider, "Plain");
  34.  
  35. // add a slider with major and minor ticks
  36.  
  37. //添加一个有大和小刻度的滑块
  38. slider = new JSlider();
  39. slider.setPaintTicks(true);
  40. slider.setMajorTickSpacing(20);
  41. slider.setMinorTickSpacing(5);
  42. addSlider(slider, "Ticks");
  43.  
  44. // add a slider that snaps to ticks
  45.  
  46. slider = new JSlider();
  47. slider.setPaintTicks(true);//设置标尺标记
  48. slider.setSnapToTicks(true);
  49. slider.setMajorTickSpacing(20);//每20个单位的位置显示一个大标尺标记
  50. slider.setMinorTickSpacing(5);//每5个单位的位置显示一个小标尺标记
  51. addSlider(slider, "Snap to ticks");
  52.  
  53. // add a slider with no track
  54. //添加一个没有轨道的滑块
  55. slider = new JSlider();
  56. slider.setPaintTicks(true);
  57. slider.setMajorTickSpacing(20);
  58. slider.setMinorTickSpacing(5);
  59. slider.setPaintTrack(false);
  60. addSlider(slider, "No track");//添加滑块“无磁块”
  61.  
  62. // add an inverted slider
  63. //添加一个倒滑块
  64. slider = new JSlider();
  65. slider.setPaintTicks(true);
  66. slider.setMajorTickSpacing(20);
  67. slider.setMinorTickSpacing(5);
  68. slider.setInverted(true);
  69. addSlider(slider, "Inverted");
  70.  
  71. // add a slider with numeric labels
  72.  
  73. slider = new JSlider();
  74. slider.setPaintTicks(true);
  75. slider.setPaintLabels(true);
  76. slider.setMajorTickSpacing(20);
  77. slider.setMinorTickSpacing(5);
  78. addSlider(slider, "Labels");
  79.  
  80. // add a slider with alphabetic labels
  81.  
  82. slider = new JSlider();
  83. slider.setPaintLabels(true);
  84. slider.setPaintTicks(true);
  85. slider.setMajorTickSpacing(20);
  86. slider.setMinorTickSpacing(5);
  87.  
  88. Dictionary<Integer, Component> labelTable = new Hashtable<>();
  89. labelTable.put(0, new JLabel("A"));
  90. labelTable.put(20, new JLabel("B"));
  91. labelTable.put(40, new JLabel("C"));
  92. labelTable.put(60, new JLabel("D"));
  93. labelTable.put(80, new JLabel("E"));
  94. labelTable.put(100, new JLabel("F"));
  95.  
  96. slider.setLabelTable(labelTable);
  97. addSlider(slider, "Custom labels");
  98.  
  99. // add a slider with icon labels
  100. //添加带有数字标签的滑块
  101.  
  102. slider = new JSlider();
  103. slider.setPaintTicks(true);
  104. slider.setPaintLabels(true);//滑块设置面板标签
  105. slider.setSnapToTicks(true);
  106. slider.setMajorTickSpacing(20);
  107. slider.setMinorTickSpacing(20);
  108.  
  109. labelTable = new Hashtable<Integer, Component>();
  110.  
  111. // add card images
  112.  
  113. labelTable.put(0, new JLabel(new ImageIcon("nine.gif")));
  114. labelTable.put(20, new JLabel(new ImageIcon("ten.gif")));
  115. labelTable.put(40, new JLabel(new ImageIcon("jack.gif")));
  116. labelTable.put(60, new JLabel(new ImageIcon("queen.gif")));
  117. labelTable.put(80, new JLabel(new ImageIcon("king.gif")));
  118. labelTable.put(100, new JLabel(new ImageIcon("ace.gif")));
  119.  
  120. slider.setLabelTable(labelTable);
  121. addSlider(slider, "Icon labels");
  122.  
  123. // add the text field that displays the slider value
  124.  
  125. textField = new JTextField();
  126. add(sliderPanel, BorderLayout.CENTER);
  127. add(textField, BorderLayout.SOUTH);
  128. pack();
  129. }
  130.  
  131. /**
  132. * Adds a slider to the slider panel and hooks up the listener
  133. * @param s the slider
  134. * @param description the slider description
  135. */
  136. public void addSlider(JSlider s, String description)
  137. {
  138. s.addChangeListener(listener);
  139. JPanel panel = new JPanel();
  140. panel.add(s);
  141. panel.add(new JLabel(description));
  142. panel.setAlignmentX(Component.LEFT_ALIGNMENT);//设置组件
  143. GridBagConstraints gbc = new GridBagConstraints();
  144. gbc.gridy = sliderPanel.getComponentCount();
  145. gbc.anchor = GridBagConstraints.WEST;
  146. sliderPanel.add(panel, gbc);
  147. }
  148. }

slider

  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();//生成 SliderFrame类的GUI界面对象
  16. frame.setTitle("SliderTest");
  17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);////关闭界面的按钮操作
  18. frame.setVisible(true);//使结果可见
  19. });
  20. }

SliderTest

结果:

测试程序8

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

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

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

  1. package menu;
  2.  
  3. import java.awt.event.*;
  4. import javax.swing.*;
  5.  
  6. /**
  7. * A frame with a sample menu bar.
  8. */
  9. public class MenuFrame extends JFrame
  10. {
  11. private static final int DEFAULT_WIDTH = 300;
  12. private static final int DEFAULT_HEIGHT = 200;
  13. private Action saveAction;
  14. private Action saveAsAction;
  15. private JCheckBoxMenuItem readonlyItem;
  16. private JPopupMenu popup;
  17.  
  18. /**
  19. * A sample action that prints the action name to System.out
  20. */
  21. class TestAction extends AbstractAction
  22. {
  23. public TestAction(String name)
  24. {
  25. super(name);
  26. }
  27.  
  28. public void actionPerformed(ActionEvent event)
  29. {
  30. System.out.println(getValue(Action.NAME) + " selected.");
  31. }
  32. }
  33.  
  34. public MenuFrame()
  35. {
  36. setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
  37.  
  38. JMenu fileMenu = new JMenu("File");
  39. fileMenu.add(new TestAction("New"));
  40.  
  41. // demonstrate accelerators
  42.  
  43. JMenuItem openItem = fileMenu.add(new TestAction("Open"));
  44. openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
  45.  
  46. fileMenu.addSeparator();
  47.  
  48. saveAction = new TestAction("Save");
  49. JMenuItem saveItem = fileMenu.add(saveAction);
  50. saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
  51.  
  52. saveAsAction = new TestAction("Save As");
  53. fileMenu.add(saveAsAction);
  54. fileMenu.addSeparator();
  55.  
  56. fileMenu.add(new AbstractAction("Exit")
  57. {
  58. public void actionPerformed(ActionEvent event)
  59. {
  60. System.exit(0);
  61. }
  62. });
  63.  
  64. // demonstrate checkbox and radio button menus
  65.  
  66. readonlyItem = new JCheckBoxMenuItem("Read-only");
  67. readonlyItem.addActionListener(new ActionListener()
  68. {
  69. public void actionPerformed(ActionEvent event)
  70. {
  71. boolean saveOk = !readonlyItem.isSelected();
  72. saveAction.setEnabled(saveOk);
  73. saveAsAction.setEnabled(saveOk);
  74. }
  75. });
  76.  
  77. ButtonGroup group = new ButtonGroup();
  78.  
  79. JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert");
  80. insertItem.setSelected(true);
  81. JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype");
  82.  
  83. group.add(insertItem);
  84. group.add(overtypeItem);
  85.  
  86. // demonstrate icons
  87.  
  88. Action cutAction = new TestAction("Cut");
  89. cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
  90. Action copyAction = new TestAction("Copy");
  91. copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif"));
  92. Action pasteAction = new TestAction("Paste");
  93. pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif"));
  94.  
  95. JMenu editMenu = new JMenu("Edit");
  96. editMenu.add(cutAction);
  97. editMenu.add(copyAction);
  98. editMenu.add(pasteAction);
  99.  
  100. // demonstrate nested menus
  101.  
  102. JMenu optionMenu = new JMenu("Options");
  103.  
  104. optionMenu.add(readonlyItem);
  105. optionMenu.addSeparator();
  106. optionMenu.add(insertItem);
  107. optionMenu.add(overtypeItem);
  108.  
  109. editMenu.addSeparator();
  110. editMenu.add(optionMenu);
  111.  
  112. // demonstrate mnemonics
  113.  
  114. JMenu helpMenu = new JMenu("Help");
  115. helpMenu.setMnemonic('H');
  116.  
  117. JMenuItem indexItem = new JMenuItem("Index");
  118. indexItem.setMnemonic('I');
  119. helpMenu.add(indexItem);
  120.  
  121. // you can also add the mnemonic key to an action
  122. Action aboutAction = new TestAction("About");
  123. aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));
  124. helpMenu.add(aboutAction);
  125.  
  126. // add all top-level menus to menu bar
  127.  
  128. JMenuBar menuBar = new JMenuBar();
  129. setJMenuBar(menuBar);
  130.  
  131. menuBar.add(fileMenu);
  132. menuBar.add(editMenu);
  133. menuBar.add(helpMenu);
  134.  
  135. // demonstrate pop-ups
  136.  
  137. popup = new JPopupMenu();
  138. popup.add(cutAction);
  139. popup.add(copyAction);
  140. popup.add(pasteAction);
  141.  
  142. JPanel panel = new JPanel();
  143. panel.setComponentPopupMenu(popup);
  144. add(panel);
  145. }
  146. }

menu

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

menu

测试程序9(组内实验)

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

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

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

  1. package toolBar;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6.  
  7. /**
  8. * A frame with a toolbar and menu for color changes.
  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. // add a panel for color change
  21.  
  22. panel = new JPanel();//创建新的JPanel
  23. add(panel, BorderLayout.CENTER);
  24.  
  25. // set up actions
  26. //建立动作
  27.  
  28. Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
  29. Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
  30. Color.YELLOW);
  31. Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
  32.  
  33. Action exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif"))
  34. {
  35. public void actionPerformed(ActionEvent event)
  36. {
  37. System.exit(0);
  38. }
  39. };
  40. exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");
  41.  
  42. // populate toolbar
  43.  
  44. JToolBar bar = new JToolBar();
  45. bar.add(blueAction);//用Action对象填充工具栏
  46. bar.add(yellowAction);
  47. bar.add(redAction);
  48. bar.addSeparator();//用分隔符将按钮分组
  49. bar.add(exitAction);
  50. add(bar, BorderLayout.NORTH);
  51.  
  52. // populate menu
  53.  
  54. JMenu menu = new JMenu("Color");//显示颜色的菜单
  55. menu.add(yellowAction);//在菜单添加颜色动作
  56. menu.add(blueAction);
  57. menu.add(redAction);
  58. menu.add(exitAction);
  59. JMenuBar menuBar = new JMenuBar();
  60. menuBar.add(menu);
  61. setJMenuBar(menuBar);
  62. }
  63.  
  64. /**
  65. * The color action sets the background of the frame to a given color.
  66. */
  67. class ColorAction extends AbstractAction
  68. {
  69. public ColorAction(String name, Icon icon, Color c)
  70. {
  71. putValue(Action.NAME, name);//动作名称,显示在按钮和菜单
  72. putValue(Action.SMALL_ICON, icon);//存储小图标的地方;显示在按钮、菜单项或工具栏中
  73. putValue(Action.SHORT_DESCRIPTION, name + " background");
  74. putValue("Color", c);
  75. }
  76.  
  77. public void actionPerformed(ActionEvent event)
  78. {
  79. Color c = (Color) getValue("Color");
  80. panel.setBackground(c);
  81. }
  82. }
  83. }

toolbar

  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();//生成新的ToolBarFrame类的GUI界面
  16. frame.setTitle("ToolBarTest");
  17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口界面
  18. frame.setVisible(true);//使结果可见
  19. });
  20. }

测试程序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 记录示例代码阅读理解中存在的问题与疑惑。

  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.  
  97. int n = parent.getComponentCount();
  98. for (int i = 0; i < n; i++)
  99. {
  100. Component c = parent.getComponent(i);
  101. if (c.isVisible())
  102. {
  103. double angle = 2 * Math.PI * i / n;
  104.  
  105. // center point of component
  106. int x = xcenter + (int) (Math.cos(angle) * radius);
  107. int y = ycenter + (int) (Math.sin(angle) * radius);
  108.  
  109. // move component so that its center is (x, y)
  110. // and its size is its preferred size
  111. Dimension d = c.getPreferredSize();
  112. c.setBounds(x - d.width / 2, y - d.height / 2, d.width, d.height);
  113. }
  114. }
  115. }
  116. }

CircleLayout

  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. {//调用add方法来添加各种按钮
  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

  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. //为每个选项设置一个单选按钮
  25. for (String option : options)
  26. {
  27. JRadioButton b = new JRadioButton(option);
  28. b.setActionCommand(option);
  29. add(b);
  30. group.add(b);
  31. b.setSelected(option == options[0]);
  32. }
  33. }
  34.  
  35. /**
  36. * Gets the currently selected option.
  37. * @return the label of the currently selected radio button.
  38. */
  39. public String getSelection()
  40. {
  41. return group.getSelection().getActionCommand();
  42. }
  43. }

Button

  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");//设置标题为CircleLayoutTest
  17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭界面操作
  18. frame.setVisible(true);
  19. });
  20. }
  21. }

main

测试程序12

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

l 掌握选项对话框的用法。

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

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

option

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

option

测试程序13

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

l 掌握对话框的创建方法;

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

  1. package optionDialog;
  2.  
  3. package dialog;
  4.  
  5. import javax.swing.JFrame;
  6. import javax.swing.JMenu;
  7. import javax.swing.JMenuBar;
  8. import javax.swing.JMenuItem;
  9.  
  10. /**
  11. * A frame with a menu whose File->About action shows a dialog.
  12. */
  13. public class DialogFrame extends JFrame
  14. {//定义长和宽的大小
  15. private static final int DEFAULT_WIDTH = 300;
  16. private static final int DEFAULT_HEIGHT = 200;
  17. private AboutDialog dialog;
  18.  
  19. public DialogFrame()
  20. {
  21. setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
  22.  
  23. // Construct a File menu.
  24.  
  25. JMenuBar menuBar = new JMenuBar();
  26. setJMenuBar(menuBar);
  27. JMenu fileMenu = new JMenu("File");
  28. menuBar.add(fileMenu);
  29.  
  30. // Add About and Exit menu items.
  31.  
  32. // The About item shows the About dialog.
  33.  
  34. JMenuItem aboutItem = new JMenuItem("About");//建立新的对话框现象
  35. aboutItem.addActionListener(event -> {//并让他可见
  36. if (dialog == null) // first time
  37. dialog = new AboutDialog(DialogFrame.this);
  38. dialog.setVisible(true); // pop up dialog
  39. });
  40. fileMenu.add(aboutItem);
  41.  
  42. // The Exit item exits the program.
  43. //按Exit退出程序
  44.  
  45. JMenuItem exitItem = new JMenuItem("Exit");
  46. exitItem.addActionListener(event -> System.exit(0));
  47. fileMenu.add(exitItem);
  48. }
  49. }

DialogFrame

  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. {
  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);//将HTML标签添加到中心
  26.  
  27. // OK button closes the dialog
  28. //OK按钮关闭对话框
  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. }

AboutDialog

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

测试程序14

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

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

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

  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())) + "\n");
  64. }
  65. }
  66. }
  67. }

DataExchangeFrame

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

Password

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

User

测试程序15

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

l 掌握文件对话框的用法;

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

  1. package fileChooser;
  2.  
  3. import java.awt.*;
  4. import java.io.*;
  5.  
  6. import javax.swing.*;
  7.  
  8. /**
  9. * A file chooser accessory that previews images.
  10. */
  11. public class ImagePreviewer extends JLabel
  12. {
  13. /**
  14. * Constructs an ImagePreviewer.
  15. * @param chooser the file chooser whose property changes trigger an image
  16. * change in this previewer
  17. */
  18. public ImagePreviewer(JFileChooser chooser)
  19. {
  20. setPreferredSize(new Dimension(100, 100));//设置此组件的首选大小
  21. setBorder(BorderFactory.createEtchedBorder());//设置此组件的边框
  22.  
  23. chooser.addPropertyChangeListener(event -> {
  24. if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
  25. {
  26. // the user has selected a new file
  27. File f = (File) event.getNewValue();//创建一个新的文件对话框
  28. if (f == null)
  29. {
  30. setIcon(null);
  31. return;
  32. }
  33.  
  34. // read the image into an icon
  35. //将图像读成图标
  36. ImageIcon icon = new ImageIcon(f.getPath());
  37.  
  38. // if the icon is too large to fit, scale it
  39. //如果图标太大而无法容纳,将其缩放
  40. if (icon.getIconWidth() > getWidth())
  41. icon = new ImageIcon(icon.getImage().getScaledInstance(
  42. getWidth(), -1, Image.SCALE_DEFAULT));
  43.  
  44. setIcon(icon);//图标
  45. }
  46. });
  47. }
  48. }

ImagePreviewer

  1. package fileChooser;
  2.  
  3. import java.io.*;
  4.  
  5. import javax.swing.*;
  6. import javax.swing.filechooser.*;
  7. import javax.swing.filechooser.FileFilter;
  8.  
  9. /**
  10. * A frame that has a menu for loading an image and a display area for the
  11. * loaded image.
  12. */
  13. public class ImageViewerFrame extends JFrame
  14. {
  15. private static final int DEFAULT_WIDTH = 300;
  16. private static final int DEFAULT_HEIGHT = 400;
  17. private JLabel label;
  18. private JFileChooser chooser;
  19.  
  20. public ImageViewerFrame()
  21. {
  22. setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
  23.  
  24. // set up menu bar
  25. JMenuBar menuBar = new JMenuBar();
  26. setJMenuBar(menuBar);
  27.  
  28. JMenu menu = new JMenu("File");
  29. menuBar.add(menu);
  30.  
  31. JMenuItem openItem = new JMenuItem("Open");
  32. menu.add(openItem);
  33. openItem.addActionListener(event -> {
  34. chooser.setCurrentDirectory(new File("."));
  35.  
  36. // show file chooser dialog
  37. int result = chooser.showOpenDialog(ImageViewerFrame.this);
  38.  
  39. // if image file accepted, set it as icon of the label
  40. if (result == JFileChooser.APPROVE_OPTION)
  41. {
  42. String name = chooser.getSelectedFile().getPath();
  43. label.setIcon(new ImageIcon(name));
  44. pack();
  45. }
  46. });
  47.  
  48. JMenuItem exitItem = new JMenuItem("Exit");
  49. menu.add(exitItem);
  50. exitItem.addActionListener(event -> System.exit(0));
  51.  
  52. // use a label to display the images
  53. //使用一个标签来显示图像标签
  54. label = new JLabel();
  55. add(label);
  56.  
  57. // set up file chooser
  58. //设置文件选择器
  59. chooser = new JFileChooser();
  60.  
  61. // accept all image files ending with .jpg, .jpeg, .gif
  62.  
  63. FileFilter filter = new FileNameExtensionFilter(
  64. "Image files", "jpg", "jpeg", "gif");//接受各种形式
  65. chooser.setFileFilter(filter);
  66.  
  67. chooser.setAccessory(new ImagePreviewer(chooser));
  68. //设置过滤器
  69. chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif")));
  70. }
  71. }

ImageViewerFrame

  1. package fileChooser;
  2.  
  3. import java.io.*;
  4. import javax.swing.*;
  5. import javax.swing.filechooser.*;
  6. import javax.swing.filechooser.FileFilter;
  7.  
  8. /**
  9. * A file view that displays an icon for all files that match a file filter.
  10. */
  11. public class FileIconView extends FileView
  12. {
  13. private FileFilter filter;
  14. private Icon icon;
  15.  
  16. /**
  17. * Constructs a FileIconView.
  18. * @param aFilter a file filter--all files that this filter accepts will be shown
  19. * with the icon.
  20. * @param anIcon--the icon shown with all accepted files.
  21. */
  22. public FileIconView(FileFilter aFilter, Icon anIcon)
  23. {
  24. filter = aFilter;
  25. icon = anIcon;
  26. }
  27.  
  28. public Icon getIcon(File f)
  29. {
  30. if (!f.isDirectory() && filter.accept(f)) return icon;
  31. else return null;
  32. }
  33. }

FileIcon

  1. package fileChooser;
  2.  
  3. import java.awt.*;
  4. import javax.swing.*;
  5.  
  6. /**
  7. * @version 1.25 2015-06-12
  8. * @author Cay Horstmann
  9. */
  10. public class FileChooserTest
  11. {
  12. public static void main(String[] args)
  13. {
  14. EventQueue.invokeLater(() -> {
  15. JFrame frame = new ImageViewerFrame();
  16. frame.setTitle("FileChooserTest");
  17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  18. frame.setVisible(true);
  19. });
  20. }
  21. }

测试程序16

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

l 了解颜色选择器的用法。

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

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

ColorChooser

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

ColorChooserFrame

  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();//生成ColorChooserFrame类
  16. frame.setTitle("ColorChooserTest");
  17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭界面操作
  18. frame.setVisible(true);
  19. });
  20. }
  21. }

ColorChooserTest

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

总结:我们组这次所分析的是工具栏和工具提示的用法方面的知识,工具栏(Toolbar Test)是在程序中提供的快速访问常用命令的按纽栏,它可以随意的移动安放,可以用JToolBar bar=new JToolBar();来创建工具栏。但工具栏有缺点,为了便利用户能快速明白小按钮的含义,用户界面设计者发明了工具提示toooltips,示例程序说明了如何将一个Action对象添加到菜单和工具栏中。通过代码解读和注释,我们可以明白如何去构建一个工具栏,将组建添加到工具栏中,因此实现工具栏的功能。

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

具体见QQ群

201771010135 杨蓉庆/张燕/杨玲《面对对象程序设计(java)》第十四周学习总结的更多相关文章

  1. 201771010135 杨蓉庆/张燕《面对对象程序设计(java)》第十三周学习总结

    1.实验目的与要求 (1) 掌握事件处理的基本原理,理解其用途: (2) 掌握AWT事件模型的工作机制: (3) 掌握事件处理的基本编程模型: (4) 了解GUI界面组件观感设置方法: (5) 掌握W ...

  2. 201771010142 张燕& 杨蓉庆 实验十一 集合

    实验十一   集合 实验时间 2018-11-8 一  理论知识 一般将数据结构分为两大类:线性数据结构和非线性数据结构.线性数据结构:线性表.栈.队列.串.数组和文件.非线性数据结构:树和图. 线性 ...

  3. 201771010135 杨蓉庆AND张燕 《面对对象程序设计(java)》第十一周学习总结

    1.实验目的与要求 (1) 掌握Vetor.Stack.Hashtable三个类的用途及常用API: (2) 了解java集合框架体系组成: (3) 掌握ArrayList.LinkList两个类的用 ...

  4. 实验十四 第九组 张燕~杨蓉庆~杨玲 Swing图形界面组件

    实验十四  Swing图形界面组件 8-11-29 理论知识 Swing和MVC设计模式 (1)设计模式(Design pattern)是设计者一种流行的 思考设计问题的方法,是一套被反复使用,多数人 ...

  5. 201771010135 杨蓉庆《面对对象程序设计(java)》第十八周学习总结

    1.实验目的与要求 (1) 综合掌握java基本程序结构: (2) 综合掌握java面向对象程序设计特点: (3) 综合掌握java GUI 程序设计结构: (4) 综合掌握java多线程编程模型: ...

  6. 201771010135 杨蓉庆《面对对象程序设计(java)》第十七周学习总结

    1.实验目的与要求 (1) 掌握线程同步的概念及实现技术: (2) 线程综合编程练习 一.理论知识 ⚫ 线程同步 (1)多线程并发运行不确定性问题解决方案:引入线 程同步机制,使得另一线程要使用该方法 ...

  7. 201771010135 杨蓉庆《面对对象程序设计(java)》第十六周学习总结

    1.实验目的与要求 (1) 掌握线程概念: (2) 掌握线程创建的两种技术: (3) 理解和掌握线程的优先级属性及调度方法: (4) 掌握线程同步的概念及实现技术: 一.理论知识 ⚫ 线程的概念 (1 ...

  8. 201771010135 杨蓉庆《面对对象程序设计(java)》第十五周学习总结

    1.实验目的与要求 (1) 掌握Java应用程序的打包操作: (2) 了解应用程序存储配置信息的两种方法: (3) 掌握基于JNLP协议的java Web Start应用程序的发布方法: (5) 掌握 ...

  9. 201771010135 杨蓉庆《面对对象程序设计(java)》第十二周学习总结

    1.实验目的与要求 (1) 掌握Java GUI中框架创建及属性设置中常用类的API: (2) 掌握Java GUI中2D图形绘制常用类的API: (3) 了解Java GUI中2D图形中字体与颜色的 ...

随机推荐

  1. Freezable 对象概述 | Microsoft Docs

    原文:Freezable 对象概述 | Microsoft Docs Freezable 对象概述Freezable Objects Overview 2017/03/30 本文内容 什么是可冻结的? ...

  2. g++运行c++程序提示main()找不到

    /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In function `_start': (.text+0x20) ...

  3. 2019牛客多校第五场C generator 2 hash,bsgs模板

    generator 2 题意 给出\(x_0,a,b,p\),有方程\(x_i\equiv (a*x_{i-1}+b)(\% p)\),求最小的i,使得\(x_i=v\),不存在输出-1 分析 经过公 ...

  4. LED Decorative Light Supplier - LED Neon Application: 5 Advantages

    In the past 100 years, lighting has gone a long way. LED decorative lighting is now designed to meet ...

  5. Python之路Day05

    字典 字典 -- dict Python的数据结构之一 字典是可变数据类型,无序的 定义 dic = {'key':'Value'} 键值对 字典的作用 存储数据,大大量的,将数据和数据起到关联作用 ...

  6. <img src = "..."/>的一个图片上面怎么在放上字

    转自:https://zhidao.baidu.com/question/1495805873400412779.html 例子1: html中可以用css相对定位让文字在图片的上面. 1.新建htm ...

  7. elementui el-table根据分页显示表格序号

    每页显示的序号都是一样的: <el-table :data="tableData" highlight-current-row @current-change="h ...

  8. Python(三):环境及其配置

    一,PYTHONPATH 默认的Python模块搜索路径,可以将路径指向anaconda3,需要开发者自己设置 二,PYTHONHASHSEED 如果该环境变量被设定为 random ,相当于 -R ...

  9. 题解【洛谷P1807】最长路_NOI导刊2010提高(07)

    题面 题解 最长路模板. 只需要在最短路的模板上把符号改一下\(+\)初值赋为\(-1\)即可. 注意一定是单向边,不然出现了正环就没有最长路了,就好比出现了负环就没有最短路了. 只能用\(SPFA\ ...

  10. CentOS 7下用firewall-cmd控制端口与端口转发

    # 将80端口的流量转发至192.168.0.1的8080端口 1.firewall-cmd --permanent --add-forward-port=port=80:proto=tcp:toad ...