实验十四  Swing图形界面组件

实验时间 20178-11-29

1、实验目的与要求

(1)设计模式:反复使用、经过分类编目的、代码设计经验的总结。

在Alexander的模式分类和软件模式的分类中,每种模式都遵循一种特定的格式。

模型-视图-控制器模式并不是AWT和Swing设计中使用的唯一模式;下列是应用的另外几种模式:容器和组件是“组合(composite)”模式;带滚动条的面板是“装饰器(decorator)”模式;布局管理器是“策略(strategy)”模式。

每个组件都有的三要素:内容;外观(颜色、大小等);行为(对事件的反应)。

模型-视图-控制器(MVC)模式告诉我们如何实现这种设计,实现三个独立的类:模型(model):存储内容;视图(view):显示内容;控制器(controller):处理用户输入。

模型必须实现改变内容和查找内容的方法(模型是完全不可见的)。

模型-视图-控制器模式的一个优点是一个模型可以有多个视图,其中每个视图可以显示全部内容的不同部分或不同形式。

需要注意的是,同样的模型可用于下压按钮、单选按钮、复选框、甚至是菜单项。

(2) 由于在JDK中没有表单设计器,所以需要通过编写代码来定制(布局)用户界面组件所在的位置。

通常,组件放置在容器中,布局管理器决定容器中的组件具体放置的位置和大小。

按钮、文本域和其它用户界面元素都继承于Component类,组件可以放置在面板这样的容器中。

2、实验内容和步骤

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

测试程序1

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

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

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

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

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 = ;//result置为0
lastCommand = "=";
start = true; // add the display display = new JButton("");//计算结果的显示内容
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容器组件
panel.setLayout(new GridLayout(, ));//定义网格管理器4行4列的网格 addButton("", insert);
addButton("", insert);
addButton("", insert);
addButton("/", command); addButton("", insert);
addButton("", insert);
addButton("", insert);
addButton("*", command); addButton("", insert);//insert动作监听器类
addButton("", insert);
addButton("", insert);
addButton("-", command);//command命令 addButton("", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);//调用addButton方法,定义私有的方法,生成16个事件源 add(panel, BorderLayout.CENTER); JButton b1= new JButton("验证");
add(b1,BorderLayout.SOUTH); JButton b2= new JButton("验证1");
add(b2,BorderLayout.WEST); JButton b3= new JButton("验证2");
add(b3,BorderLayout.EAST);
} /**
* Adds a button to the center panel.
* @param label the button label
* @param listener the button listener
*/
private void addButton(String label, ActionListener listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
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();//封装在event中 if (start)
{
if (command.equals("-"))
{
display.setText(command);
start = false;
}
else lastCommand = command;
}
else
{
calculate(Double.parseDouble(display.getText()));//把display的数字字符串通过 parseDouble转换为数字
lastCommand = command;
start = true;
}
}
} /**
* Carries out the pending calculation.
* @param x the value to be accumulated with the prior result.
*/
public void calculate(double x)
{
if (lastCommand.equals("+")) result += x;
else if (lastCommand.equals("-")) result -= x;
else if (lastCommand.equals("*")) result *= x;
else if (lastCommand.equals("/")) result /= x;
else if (lastCommand.equals("=")) result = x;
display.setText("" + result);//setText的空字符串不能去掉,要进行字符串转换,转换为数字字符串
}
}

修改添加后的代码:

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 = ;//result置为0
lastCommand = "=";
start = true; // add the display display = new JButton("");//计算结果的显示内容
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容器组件
panel.setLayout(new GridLayout(, ));//定义网格管理器4行4列的网格 addButton("", insert);
addButton("", insert);
addButton("", insert);
addButton("/", command); addButton("", insert);
addButton("", insert);
addButton("", insert);
addButton("*", command); addButton("", insert);
addButton("", insert);
addButton("", insert);
addButton("-", command); addButton("", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);//调用addButton方法,定义私有的方法,生成16个事件源 add(panel, BorderLayout.CENTER); JButton b1= new JButton("验证");
add(b1,BorderLayout.SOUTH); JButton b2= new JButton("验证1");
add(b2,BorderLayout.WEST); JButton b3= new JButton("验证2");
add(b3,BorderLayout.EAST);
} /**
* Adds a button to the center panel.
* @param label the button label
* @param listener the button listener
*/
private void addButton(String label, ActionListener listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
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;

import java.awt.*;
import javax.swing.*; /**
* @version 1.41 2015-06-12
* @author Cay Horstmann
*/
public class TextComponentTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new TextComponentFrame();
frame.setTitle("TextComponentTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}

package text;

import java.awt.BorderLayout;
import java.awt.GridLayout; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants; /**
* A frame with sample text components.
*/
public class TextComponentFrame extends JFrame
{
public static final int TEXTAREA_ROWS = ;//定义行
public static final int TEXTAREA_COLUMNS = ;//定义列 public TextComponentFrame()//构造器
{
JTextField textField = new JTextField();
JPasswordField passwordField = new JPasswordField(); JPanel northPanel = new JPanel();
northPanel.setLayout(new GridLayout(, ));//网格布局管理器:2行2列
northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT));
northPanel.add(textField);//将文本域添加到窗口
northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT));
northPanel.add(passwordField);//将密码输入框添加到窗口 add(northPanel, BorderLayout.NORTH);//显示在窗口的上方 JTextArea textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS);
JScrollPane scrollPane = new JScrollPane(textArea); add(scrollPane, BorderLayout.CENTER);//显示在窗口中心 // 添加按钮,将文本追加到文本区域 JPanel southPanel = new JPanel(); JButton insertButton = new JButton("Insert");//定义Button按钮:insert
southPanel.add(insertButton);//添加insert按钮
insertButton.addActionListener(event ->
textArea.append("User name: " + textField.getText() + " Password: "
+ new String(passwordField.getPassword()) + "\n")); add(southPanel, BorderLayout.SOUTH);//显示在窗口下方
pack();
}
}

测试程序3

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

掌握复选框组件的用法;

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

package checkBox;

import java.awt.*;
import javax.swing.*; /**
* @version 1.34 2015-06-12
* @author Cay Horstmann
*/
public class CheckBoxTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new CheckBoxFrame();
frame.setTitle("CheckBoxTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}

测试程序4

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

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

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

package radioButton;

import java.awt.*;
import javax.swing.*; /**
* @version 1.34 2015-06-12
* @author Cay Horstmann
*/
public class RadioButtonTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new RadioButtonFrame();
frame.setTitle("RadioButtonTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}

测试程序5

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

掌握边框的用法;

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

package border;

import java.awt.*;
import javax.swing.*; /**
* @version 1.34 2015-06-13
* @author Cay Horstmann
*/
public class BorderTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new BorderFrame();
frame.setTitle("BorderTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}

测试程序6

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

掌握组合框组件的用法;

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

package comboBox;

import java.awt.*;
import javax.swing.*; /**
* @version 1.35 2015-06-12
* @author Cay Horstmann
*/
public class ComboBoxTest
{
public static void main(String[] args)
{
//lambda表达式
EventQueue.invokeLater(() -> {
//构造frame框架对象
JFrame frame = new ComboBoxFrame();
//设置标题
frame.setTitle("ComboBoxTest");
//设置用户在此窗体上发起 "close" 时默认执行的操作。
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置框架是否可见
frame.setVisible(true);
});
}
}
package comboBox;

import java.awt.BorderLayout;
import java.awt.Font; import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel; /**
* 具有示例文本标签和用于选择字体外观的组合框的框架。
* 组合框:将按钮或可编辑字段与下拉列表组合的组件。
* 用户可以从下拉列表中选择值,下拉列表在用户请求时显示。
* 如果使组合框处于可编辑状态,则组合框将包括用户可在其中键入值的可编辑字段。
*/ //ComboBoxFrame继承于JFrame类
public class ComboBoxFrame extends JFrame
{
//设置ComboBoxFrame的私有属性
private JComboBox<String> faceCombo;
private JLabel label;
private static final int DEFAULT_SIZE = ; public ComboBoxFrame()
{
// 添加示例文本标签 label = new JLabel("The quick brown fox jumps over the lazy dog.");
//设置字体
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
//添加到边框布局管理器的中间
add(label, BorderLayout.CENTER); // 创建一个组合框对象并添加项目名称 faceCombo = new JComboBox<>();
//把一个选项添加到选项列表中,有五种选项
faceCombo.addItem("Serif");
faceCombo.addItem("SansSerif");
faceCombo.addItem("Monospaced");
faceCombo.addItem("Dialog");
faceCombo.addItem("DialogInput"); // 组合框监听器将标签字体更改为所选的名称(添加监听器,使用lambda表达式) faceCombo.addActionListener(event ->
//设置标签的字体
label.setFont(
//getItemAt用于返回指定索引处的列表项;getSelectedIndex用于返回当前选择的选项
new Font(faceCombo.getItemAt(faceCombo.getSelectedIndex()),
Font.PLAIN, DEFAULT_SIZE))); // 将组合框添加到框架南部边界的面板 JPanel comboPanel = new JPanel();
comboPanel.add(faceCombo);
add(comboPanel, BorderLayout.SOUTH);
pack();
}
}

测试程序7

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

掌握滑动条组件的用法;

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

package slider;

import java.awt.*;
import javax.swing.*; /**
* @version 1.15 2015-06-12
* @author Cay Horstmann
*/
public class SliderTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
SliderFrame frame = new SliderFrame();
frame.setTitle("SliderTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package slider;

import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*; /**
* A frame with many sliders and a text field to show slider values.
*/
public class SliderFrame extends JFrame
{
private JPanel sliderPanel;
private JTextField textField;
private ChangeListener listener; public SliderFrame()
{
sliderPanel = new JPanel();
sliderPanel.setLayout(new GridBagLayout()); // common listener for all sliders
listener = event -> {
// update text field when the slider value changes
JSlider source = (JSlider) event.getSource();
textField.setText("" + source.getValue());
}; // add a plain slider JSlider slider = new JSlider();
addSlider(slider, "Plain"); // add a slider with major and minor ticks slider = new JSlider();
slider.setPaintTicks(true);
slider.setMajorTickSpacing();
slider.setMinorTickSpacing();
addSlider(slider, "Ticks"); // add a slider that snaps to ticks slider = new JSlider();
slider.setPaintTicks(true);
slider.setSnapToTicks(true);
slider.setMajorTickSpacing();
slider.setMinorTickSpacing();
addSlider(slider, "Snap to ticks"); // add a slider with no track slider = new JSlider();
slider.setPaintTicks(true);
slider.setMajorTickSpacing();
slider.setMinorTickSpacing();
slider.setPaintTrack(false);
addSlider(slider, "No track"); // add an inverted slider slider = new JSlider();
slider.setPaintTicks(true);
slider.setMajorTickSpacing();
slider.setMinorTickSpacing();
slider.setInverted(true);
addSlider(slider, "Inverted"); // add a slider with numeric labels slider = new JSlider();
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setMajorTickSpacing();
slider.setMinorTickSpacing();
addSlider(slider, "Labels"); // add a slider with alphabetic labels slider = new JSlider();
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setMajorTickSpacing();
slider.setMinorTickSpacing(); Dictionary<Integer, Component> labelTable = new Hashtable<>();
labelTable.put(, new JLabel("A"));
labelTable.put(, new JLabel("B"));
labelTable.put(, new JLabel("C"));
labelTable.put(, new JLabel("D"));
labelTable.put(, new JLabel("E"));
labelTable.put(, new JLabel("F")); slider.setLabelTable(labelTable);
addSlider(slider, "Custom labels"); // add a slider with icon labels slider = new JSlider();
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setSnapToTicks(true);
slider.setMajorTickSpacing();
slider.setMinorTickSpacing(); labelTable = new Hashtable<Integer, Component>(); // add card images labelTable.put(, new JLabel(new ImageIcon("nine.gif")));
labelTable.put(, new JLabel(new ImageIcon("ten.gif")));
labelTable.put(, new JLabel(new ImageIcon("jack.gif")));
labelTable.put(, new JLabel(new ImageIcon("queen.gif")));
labelTable.put(, new JLabel(new ImageIcon("king.gif")));
labelTable.put(, new JLabel(new ImageIcon("ace.gif"))); slider.setLabelTable(labelTable);
addSlider(slider, "Icon labels"); // add the text field that displays the slider value textField = new JTextField();
add(sliderPanel, BorderLayout.CENTER);
add(textField, BorderLayout.SOUTH);
pack();
} /**
* Adds a slider to the slider panel and hooks up the listener
* @param s the slider
* @param description the slider description
*/
public void addSlider(JSlider s, String description)
{
s.addChangeListener(listener);
JPanel panel = new JPanel();
panel.add(s);
panel.add(new JLabel(description));
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = sliderPanel.getComponentCount();
gbc.anchor = GridBagConstraints.WEST;
sliderPanel.add(panel, gbc);
}
}

测试程序8

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

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

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

package menu;

import java.awt.*;
import javax.swing.*; /**
* @version 1.24 2012-06-12
* @author Cay Horstmann
*/
public class MenuTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new MenuFrame();
frame.setTitle("MenuTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package menu;

import java.awt.event.*;
import javax.swing.*; /**
* A frame with a sample menu bar.
*/
public class MenuFrame extends JFrame
{
private static final int DEFAULT_WIDTH = ;
private static final int DEFAULT_HEIGHT = ;
private Action saveAction;
private Action saveAsAction;
private JCheckBoxMenuItem readonlyItem;
private JPopupMenu popup; /**
* A sample action that prints the action name to System.out
*/
class TestAction extends AbstractAction
{
public TestAction(String name)
{
super(name);
} public void actionPerformed(ActionEvent event)
{
System.out.println(getValue(Action.NAME) + " selected.");
}
} public MenuFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); JMenu fileMenu = new JMenu("File");
fileMenu.add(new TestAction("New")); // demonstrate accelerators JMenuItem openItem = fileMenu.add(new TestAction("Open"));
openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O")); fileMenu.addSeparator(); saveAction = new TestAction("Save");
JMenuItem saveItem = fileMenu.add(saveAction);
saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S")); saveAsAction = new TestAction("Save As");
fileMenu.add(saveAsAction);
fileMenu.addSeparator(); fileMenu.add(new AbstractAction("Exit")
{
public void actionPerformed(ActionEvent event)
{
System.exit();
}
}); // demonstrate checkbox and radio button menus readonlyItem = new JCheckBoxMenuItem("Read-only");
readonlyItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
boolean saveOk = !readonlyItem.isSelected();
saveAction.setEnabled(saveOk);
saveAsAction.setEnabled(saveOk);
}
}); ButtonGroup group = new ButtonGroup(); JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert");
insertItem.setSelected(true);
JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype"); group.add(insertItem);
group.add(overtypeItem); // demonstrate icons Action cutAction = new TestAction("Cut");
cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
Action copyAction = new TestAction("Copy");
copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif"));
Action pasteAction = new TestAction("Paste");
pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif")); JMenu editMenu = new JMenu("Edit");
editMenu.add(cutAction);
editMenu.add(copyAction);
editMenu.add(pasteAction); // demonstrate nested menus JMenu optionMenu = new JMenu("Options"); optionMenu.add(readonlyItem);
optionMenu.addSeparator();
optionMenu.add(insertItem);
optionMenu.add(overtypeItem); editMenu.addSeparator();
editMenu.add(optionMenu); // demonstrate mnemonics JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H'); JMenuItem indexItem = new JMenuItem("Index");
indexItem.setMnemonic('I');
helpMenu.add(indexItem); // you can also add the mnemonic key to an action
Action aboutAction = new TestAction("About");
aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));
helpMenu.add(aboutAction); // add all top-level menus to menu bar JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar); menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu); // demonstrate pop-ups popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction); JPanel panel = new JPanel();
panel.setComponentPopupMenu(popup);
add(panel);
}
}

测试程序9

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

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

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

package toolBar;

import java.awt.*;
import javax.swing.*; /**
* @version 1.14 2015-06-12
* @author Cay Horstmann
*/
public class ToolBarTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
ToolBarFrame frame = new ToolBarFrame();
frame.setTitle("ToolBarTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package toolBar;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*; /**
* A frame with a toolbar and menu for color changes.
*/
public class ToolBarFrame extends JFrame
{
private static final int DEFAULT_WIDTH = ;
private static final int DEFAULT_HEIGHT = ;
private JPanel panel; public ToolBarFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // add a panel for color change panel = new JPanel();
add(panel, BorderLayout.CENTER); // set up actions Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
Color.YELLOW);
Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); Action exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif"))
{
public void actionPerformed(ActionEvent event)
{
System.exit();
}
};
exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit"); // populate toolbar JToolBar bar = new JToolBar();
bar.add(blueAction);
bar.add(yellowAction);
bar.add(redAction);
bar.addSeparator();
bar.add(exitAction);
add(bar, BorderLayout.NORTH); // populate menu JMenu menu = new JMenu("Color");
menu.add(yellowAction);
menu.add(blueAction);
menu.add(redAction);
menu.add(exitAction);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
} /**
* The color action sets the background of the frame to a given color.
*/
class ColorAction extends AbstractAction
{
public ColorAction(String name, Icon icon, Color c)
{
putValue(Action.NAME, name);
putValue(Action.SMALL_ICON, icon);
putValue(Action.SHORT_DESCRIPTION, name + " background");
putValue("Color", c);
} public void actionPerformed(ActionEvent event)
{
Color c = (Color) getValue("Color");
panel.setBackground(c);
}
}
}

测试程序10

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

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

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

package gridbag;

import java.awt.EventQueue;

import javax.swing.JFrame;

/**
* @version 1.35 2015-06-12
* @author Cay Horstmann
*/
public class GridBagLayoutTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new FontFrame();
frame.setTitle("GridBagLayoutTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package gridbag;

import java.awt.*;

/**
* This class simplifies the use of the GridBagConstraints class.
* @version 1.01 2004-05-06
* @author Cay Horstmann
*/
public class GBC extends GridBagConstraints
{
/**
* Constructs a GBC with a given gridx and gridy position and all other grid
* bag constraint values set to the default.
* @param gridx the gridx position
* @param gridy the gridy position
*/
public GBC(int gridx, int gridy)
{
this.gridx = gridx;
this.gridy = gridy;
} /**
* Constructs a GBC with given gridx, gridy, gridwidth, gridheight and all
* other grid bag constraint values set to the default.
* @param gridx the gridx position
* @param gridy the gridy position
* @param gridwidth the cell span in x-direction
* @param gridheight the cell span in y-direction
*/
public GBC(int gridx, int gridy, int gridwidth, int gridheight)
{
this.gridx = gridx;
this.gridy = gridy;
this.gridwidth = gridwidth;
this.gridheight = gridheight;
} /**
* Sets the anchor.
* @param anchor the anchor value
* @return this object for further modification
*/
public GBC setAnchor(int anchor)
{
this.anchor = anchor;
return this;
} /**
* Sets the fill direction.
* @param fill the fill direction
* @return this object for further modification
*/
public GBC setFill(int fill)
{
this.fill = fill;
return this;
} /**
* Sets the cell weights.
* @param weightx the cell weight in x-direction
* @param weighty the cell weight in y-direction
* @return this object for further modification
*/
public GBC setWeight(double weightx, double weighty)
{
this.weightx = weightx;
this.weighty = weighty;
return this;
} /**
* Sets the insets of this cell.
* @param distance the spacing to use in all directions
* @return this object for further modification
*/
public GBC setInsets(int distance)
{
this.insets = new Insets(distance, distance, distance, distance);
return this;
} /**
* Sets the insets of this cell.
* @param top the spacing to use on top
* @param left the spacing to use to the left
* @param bottom the spacing to use on the bottom
* @param right the spacing to use to the right
* @return this object for further modification
*/
public GBC setInsets(int top, int left, int bottom, int right)
{
this.insets = new Insets(top, left, bottom, right);
return this;
} /**
* Sets the internal padding
* @param ipadx the internal padding in x-direction
* @param ipady the internal padding in y-direction
* @return this object for further modification
*/
public GBC setIpad(int ipadx, int ipady)
{
this.ipadx = ipadx;
this.ipady = ipady;
return this;
}
}
package gridbag;

import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionListener; import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea; /**
* A frame that uses a grid bag layout to arrange font selection components.
*/
public class FontFrame extends JFrame
{
public static final int TEXT_ROWS = ;
public static final int TEXT_COLUMNS = ; private JComboBox<String> face;
private JComboBox<Integer> size;
private JCheckBox bold;
private JCheckBox italic;
private JTextArea sample; public FontFrame()
{
GridBagLayout layout = new GridBagLayout();
setLayout(layout); ActionListener listener = event -> updateSample(); // construct components JLabel faceLabel = new JLabel("Face: "); face = new JComboBox<>(new String[] { "Serif", "SansSerif", "Monospaced",
"Dialog", "DialogInput" }); face.addActionListener(listener); JLabel sizeLabel = new JLabel("Size: "); size = new JComboBox<>(new Integer[] { , , , , , , , }); size.addActionListener(listener); bold = new JCheckBox("Bold");
bold.addActionListener(listener); italic = new JCheckBox("Italic");
italic.addActionListener(listener); sample = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
sample.setText("The quick brown fox jumps over the lazy dog");
sample.setEditable(false);
sample.setLineWrap(true);
sample.setBorder(BorderFactory.createEtchedBorder()); // add components to grid, using GBC convenience class add(faceLabel, new GBC(, ).setAnchor(GBC.EAST));
add(face, new GBC(, ).setFill(GBC.HORIZONTAL).setWeight(, )
.setInsets());
add(sizeLabel, new GBC(, ).setAnchor(GBC.EAST));
add(size, new GBC(, ).setFill(GBC.HORIZONTAL).setWeight(, )
.setInsets());
add(bold, new GBC(, , , ).setAnchor(GBC.CENTER).setWeight(, ));
add(italic, new GBC(, , , ).setAnchor(GBC.CENTER).setWeight(, ));
add(sample, new GBC(, , , ).setFill(GBC.BOTH).setWeight(, ));
pack();
updateSample();
} public void updateSample()
{
String fontFace = (String) face.getSelectedItem();
int fontStyle = (bold.isSelected() ? Font.BOLD : )
+ (italic.isSelected() ? Font.ITALIC : );
int fontSize = size.getItemAt(size.getSelectedIndex());
Font font = new Font(fontFace, fontStyle, fontSize);
sample.setFont(font);
sample.repaint();
}
}
package groupLayout;

import java.awt.EventQueue;

import javax.swing.JFrame;

/**
* @version 1.01 2015-06-12
* @author Cay Horstmann
*/
public class GroupLayoutTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new FontFrame();
frame.setTitle("GroupLayoutTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}

测试程序11

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

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

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

package circleLayout;

import java.awt.*;
import javax.swing.*; /**
* @version 1.33 2015-06-12
* @author Cay Horstmann
*/
public class CircleLayoutTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new CircleLayoutFrame();
frame.setTitle("CircleLayoutTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package optionDialog;

import javax.swing.*;

/**
* A panel with radio buttons inside a titled border.
*/
public class ButtonPanel extends JPanel
{
private ButtonGroup group; /**
* Constructs a button panel.
* @param title the title shown in the border
* @param options an array of radio button labels
*/
public ButtonPanel(String title, String... options)
{
setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
group = new ButtonGroup(); // make one radio button for each option
for (String option : options)
{
JRadioButton b = new JRadioButton(option);
b.setActionCommand(option);
add(b);
group.add(b);
b.setSelected(option == options[]);
}
} /**
* Gets the currently selected option.
* @return the label of the currently selected radio button.
*/
public String getSelection()
{
return group.getSelection().getActionCommand();
}
}
package optionDialog;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*; /**
* A frame that contains settings for selecting various option dialogs.
*/
public class OptionDialogFrame extends JFrame
{
private ButtonPanel typePanel;
private ButtonPanel messagePanel;
private ButtonPanel messageTypePanel;
private ButtonPanel optionTypePanel;
private ButtonPanel optionsPanel;
private ButtonPanel inputPanel;
private String messageString = "Message";
private Icon messageIcon = new ImageIcon("blue-ball.gif");
private Object messageObject = new Date();
private Component messageComponent = new SampleComponent(); public OptionDialogFrame()
{
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(, )); typePanel = new ButtonPanel("Type", "Message", "Confirm", "Option", "Input");
messageTypePanel = new ButtonPanel("Message Type", "ERROR_MESSAGE", "INFORMATION_MESSAGE",
"WARNING_MESSAGE", "QUESTION_MESSAGE", "PLAIN_MESSAGE");
messagePanel = new ButtonPanel("Message", "String", "Icon", "Component", "Other",
"Object[]");
optionTypePanel = new ButtonPanel("Confirm", "DEFAULT_OPTION", "YES_NO_OPTION",
"YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION");
optionsPanel = new ButtonPanel("Option", "String[]", "Icon[]", "Object[]");
inputPanel = new ButtonPanel("Input", "Text field", "Combo box"); gridPanel.add(typePanel);
gridPanel.add(messageTypePanel);
gridPanel.add(messagePanel);
gridPanel.add(optionTypePanel);
gridPanel.add(optionsPanel);
gridPanel.add(inputPanel); // add a panel with a Show button JPanel showPanel = new JPanel();
JButton showButton = new JButton("Show");
showButton.addActionListener(new ShowAction());
showPanel.add(showButton); add(gridPanel, BorderLayout.CENTER);
add(showPanel, BorderLayout.SOUTH);
pack();
} /**
* Gets the currently selected message.
* @return a string, icon, component, or object array, depending on the Message panel selection
*/
public Object getMessage()
{
String s = messagePanel.getSelection();
if (s.equals("String")) return messageString;
else if (s.equals("Icon")) return messageIcon;
else if (s.equals("Component")) return messageComponent;
else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
messageComponent, messageObject };
else if (s.equals("Other")) return messageObject;
else return null;
} /**
* Gets the currently selected options.
* @return an array of strings, icons, or objects, depending on the Option panel selection
*/
public Object[] getOptions()
{
String s = optionsPanel.getSelection();
if (s.equals("String[]")) return new String[] { "Yellow", "Blue", "Red" };
else if (s.equals("Icon[]")) return new Icon[] { new ImageIcon("yellow-ball.gif"),
new ImageIcon("blue-ball.gif"), new ImageIcon("red-ball.gif") };
else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
messageComponent, messageObject };
else return null;
} /**
* Gets the selected message or option type
* @param panel the Message Type or Confirm panel
* @return the selected XXX_MESSAGE or XXX_OPTION constant from the JOptionPane class
*/
public int getType(ButtonPanel panel)
{
String s = panel.getSelection();
try
{
return JOptionPane.class.getField(s).getInt(null);
}
catch (Exception e)
{
return -;
}
} /**
* The action listener for the Show button shows a Confirm, Input, Message, or Option dialog
* depending on the Type panel selection.
*/
private class ShowAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (typePanel.getSelection().equals("Confirm")) JOptionPane.showConfirmDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel));
else if (typePanel.getSelection().equals("Input"))
{
if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
else JOptionPane.showInputDialog(OptionDialogFrame.this, getMessage(), "Title",
getType(messageTypePanel), null, new String[] { "Yellow", "Blue", "Red" },
"Blue");
}
else if (typePanel.getSelection().equals("Message")) JOptionPane.showMessageDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
else if (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel), null, getOptions(), getOptions()[]);
}
}
} /**
* A component with a painted surface
*/ class SampleComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle2D rect = new Rectangle2D.Double(, , getWidth() - , getHeight() - );
g2.setPaint(Color.YELLOW);
g2.fill(rect);
g2.setPaint(Color.BLUE);
g2.draw(rect);
} public Dimension getPreferredSize()
{
return new Dimension(, );
}
}

测试程序12

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

掌握选项对话框的用法。

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

package optionDialog;

import java.awt.*;
import javax.swing.*; /**
* @version 1.34 2015-06-12
* @author Cay Horstmann
*/
public class OptionDialogTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new OptionDialogFrame();
frame.setTitle("OptionDialogTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package optionDialog;

import javax.swing.*;

/**
* A panel with radio buttons inside a titled border.
*/
public class ButtonPanel extends JPanel
{
private ButtonGroup group; /**
* Constructs a button panel.
* @param title the title shown in the border
* @param options an array of radio button labels
*/
public ButtonPanel(String title, String... options)
{
setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
group = new ButtonGroup(); // make one radio button for each option
for (String option : options)
{
JRadioButton b = new JRadioButton(option);
b.setActionCommand(option);
add(b);
group.add(b);
b.setSelected(option == options[]);
}
} /**
* Gets the currently selected option.
* @return the label of the currently selected radio button.
*/
public String getSelection()
{
return group.getSelection().getActionCommand();
}
}
package optionDialog;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*; /**
* A frame that contains settings for selecting various option dialogs.
*/
public class OptionDialogFrame extends JFrame
{
private ButtonPanel typePanel;
private ButtonPanel messagePanel;
private ButtonPanel messageTypePanel;
private ButtonPanel optionTypePanel;
private ButtonPanel optionsPanel;
private ButtonPanel inputPanel;
private String messageString = "Message";
private Icon messageIcon = new ImageIcon("blue-ball.gif");
private Object messageObject = new Date();
private Component messageComponent = new SampleComponent(); public OptionDialogFrame()
{
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(, )); typePanel = new ButtonPanel("Type", "Message", "Confirm", "Option", "Input");
messageTypePanel = new ButtonPanel("Message Type", "ERROR_MESSAGE", "INFORMATION_MESSAGE",
"WARNING_MESSAGE", "QUESTION_MESSAGE", "PLAIN_MESSAGE");
messagePanel = new ButtonPanel("Message", "String", "Icon", "Component", "Other",
"Object[]");
optionTypePanel = new ButtonPanel("Confirm", "DEFAULT_OPTION", "YES_NO_OPTION",
"YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION");
optionsPanel = new ButtonPanel("Option", "String[]", "Icon[]", "Object[]");
inputPanel = new ButtonPanel("Input", "Text field", "Combo box"); gridPanel.add(typePanel);
gridPanel.add(messageTypePanel);
gridPanel.add(messagePanel);
gridPanel.add(optionTypePanel);
gridPanel.add(optionsPanel);
gridPanel.add(inputPanel); // add a panel with a Show button JPanel showPanel = new JPanel();
JButton showButton = new JButton("Show");
showButton.addActionListener(new ShowAction());
showPanel.add(showButton); add(gridPanel, BorderLayout.CENTER);
add(showPanel, BorderLayout.SOUTH);
pack();
} /**
* Gets the currently selected message.
* @return a string, icon, component, or object array, depending on the Message panel selection
*/
public Object getMessage()
{
String s = messagePanel.getSelection();
if (s.equals("String")) return messageString;
else if (s.equals("Icon")) return messageIcon;
else if (s.equals("Component")) return messageComponent;
else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
messageComponent, messageObject };
else if (s.equals("Other")) return messageObject;
else return null;
} /**
* Gets the currently selected options.
* @return an array of strings, icons, or objects, depending on the Option panel selection
*/
public Object[] getOptions()
{
String s = optionsPanel.getSelection();
if (s.equals("String[]")) return new String[] { "Yellow", "Blue", "Red" };
else if (s.equals("Icon[]")) return new Icon[] { new ImageIcon("yellow-ball.gif"),
new ImageIcon("blue-ball.gif"), new ImageIcon("red-ball.gif") };
else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
messageComponent, messageObject };
else return null;
} /**
* Gets the selected message or option type
* @param panel the Message Type or Confirm panel
* @return the selected XXX_MESSAGE or XXX_OPTION constant from the JOptionPane class
*/
public int getType(ButtonPanel panel)
{
String s = panel.getSelection();
try
{
return JOptionPane.class.getField(s).getInt(null);
}
catch (Exception e)
{
return -;
}
} /**
* The action listener for the Show button shows a Confirm, Input, Message, or Option dialog
* depending on the Type panel selection.
*/
private class ShowAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (typePanel.getSelection().equals("Confirm")) JOptionPane.showConfirmDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel));
else if (typePanel.getSelection().equals("Input"))
{
if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
else JOptionPane.showInputDialog(OptionDialogFrame.this, getMessage(), "Title",
getType(messageTypePanel), null, new String[] { "Yellow", "Blue", "Red" },
"Blue");
}
else if (typePanel.getSelection().equals("Message")) JOptionPane.showMessageDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
else if (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel), null, getOptions(), getOptions()[]);
}
}
} /**
* A component with a painted surface
*/ class SampleComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle2D rect = new Rectangle2D.Double(, , getWidth() - , getHeight() - );
g2.setPaint(Color.YELLOW);
g2.fill(rect);
g2.setPaint(Color.BLUE);
g2.draw(rect);
} public Dimension getPreferredSize()
{
return new Dimension(, );
}
}

测试程序13

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

掌握对话框的创建方法;

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

package dialog;

import java.awt.*;
import javax.swing.*; /**
* @version 1.34 2012-06-12
* @author Cay Horstmann
*/
public class DialogTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new DialogFrame();
frame.setTitle("DialogTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
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 = ;
private static final int DEFAULT_HEIGHT = ;
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");
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); // pop up dialog
});
fileMenu.add(aboutItem); // The Exit item exits the program. JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(event -> System.exit());
fileMenu.add(exitItem);
}
}
package dialog;

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel; /**
* A sample modal dialog that displays a message and waits for the user to click the OK button.
*/
public class AboutDialog extends JDialog
{
public AboutDialog(JFrame owner)
{
super(owner, "About DialogTest", true); // add HTML label to center add(
new JLabel(
"<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"),
BorderLayout.CENTER); // OK button closes the dialog JButton ok = new JButton("OK");
ok.addActionListener(event -> setVisible(false)); // add OK button to southern border JPanel panel = new JPanel();
panel.add(ok);
add(panel, BorderLayout.SOUTH); pack();
}
}

测试程序14

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

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

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

package dataExchange;

import java.awt.*;
import javax.swing.*; /**
* @version 1.34 2015-06-12
* @author Cay Horstmann
*/
public class DataExchangeTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new DataExchangeFrame();
frame.setTitle("DataExchangeTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package dataExchange;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*; /**
* A frame with a menu whose File->Connect action shows a password dialog.
*/
public class DataExchangeFrame extends JFrame
{
public static final int TEXT_ROWS = ;
public static final int TEXT_COLUMNS = ;
private PasswordChooser dialog = null;
private JTextArea textArea; public DataExchangeFrame()
{
// construct a File menu JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File");
mbar.add(fileMenu); // add Connect and Exit menu items JMenuItem connectItem = new JMenuItem("Connect");
connectItem.addActionListener(new ConnectAction());
fileMenu.add(connectItem); // The Exit item exits the program JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(event -> System.exit());
fileMenu.add(exitItem); textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
add(new JScrollPane(textArea), BorderLayout.CENTER);
pack();
} /**
* The Connect action pops up the password dialog.
*/
private class ConnectAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// if first time, construct dialog if (dialog == null) dialog = new PasswordChooser(); // set default values
dialog.setUser(new User("yourname", null)); // pop up dialog
if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
{
// if accepted, retrieve user input
User u = dialog.getUser();
textArea.append("user name = " + u.getName() + ", password = "
+ (new String(u.getPassword())) + "\n");
}
}
}
}

测试程序15

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

掌握文件对话框的用法;

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

package colorChooser;

import java.awt.*;
import javax.swing.*; /**
* @version 1.04 2015-06-12
* @author Cay Horstmann
*/
public class ColorChooserTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new ColorChooserFrame();
frame.setTitle("ColorChooserTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package colorChooser;

import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JPanel; /**
* A panel with buttons to pop up three types of color choosers
*/
public class ColorChooserPanel extends JPanel
{
public ColorChooserPanel()
{
JButton modalButton = new JButton("Modal");
modalButton.addActionListener(new ModalListener());
add(modalButton); JButton modelessButton = new JButton("Modeless");
modelessButton.addActionListener(new ModelessListener());
add(modelessButton); JButton immediateButton = new JButton("Immediate");
immediateButton.addActionListener(new ImmediateListener());
add(immediateButton);
} /**
* This listener pops up a modal color chooser
*/
private class ModalListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Color defaultColor = getBackground();
Color selected = JColorChooser.showDialog(ColorChooserPanel.this, "Set background",
defaultColor);
if (selected != null) setBackground(selected);
}
} /**
* This listener pops up a modeless color chooser. The panel color is changed when the user
* clicks the OK button.
*/
private class ModelessListener implements ActionListener
{
private JDialog dialog;
private JColorChooser chooser; public ModelessListener()
{
chooser = new JColorChooser();
dialog = JColorChooser.createDialog(ColorChooserPanel.this, "Background Color",
false /* not modal */, chooser,
event -> setBackground(chooser.getColor()),
null /* no Cancel button listener */);
} public void actionPerformed(ActionEvent event)
{
chooser.setColor(getBackground());
dialog.setVisible(true);
}
} /**
* This listener pops up a modeless color chooser. The panel color is changed immediately when
* the user picks a new color.
*/
private class ImmediateListener implements ActionListener
{
private JDialog dialog;
private JColorChooser chooser; public ImmediateListener()
{
chooser = new JColorChooser();
chooser.getSelectionModel().addChangeListener(
event -> setBackground(chooser.getColor())); dialog = new JDialog((Frame) null, false /* not modal */);
dialog.add(chooser);
dialog.pack();
} public void actionPerformed(ActionEvent event)
{
chooser.setColor(getBackground());
dialog.setVisible(true);
}
}
}

测试程序16

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

了解颜色选择器的用法。

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

package colorChooser;

import javax.swing.*;

/**
* A frame with a color chooser panel
*/
public class ColorChooserFrame extends JFrame
{
private static final int DEFAULT_WIDTH = ;
private static final int DEFAULT_HEIGHT = ; public ColorChooserFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // add color chooser panel to frame ColorChooserPanel panel = new ColorChooserPanel();
add(panel);
}
}
package colorChooser;

import java.awt.*;
import javax.swing.*; /**
* @version 1.04 2015-06-12
* @author Cay Horstmann
*/
public class ColorChooserTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new ColorChooserFrame();
frame.setTitle("ColorChooserTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}

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

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

 

刘志梅201771010115.《面向对象程序设计(java)》第十四周学习总结的更多相关文章

  1. 201521123061 《Java程序设计》第十四周学习总结

    201521123061 <Java程序设计>第十四周学习总结 1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多数据库相关内容. 2. 书面作业 1. MySQL数据 ...

  2. 201521123072《java程序设计》第十四周学习总结

    201521123072<java程序设计>第十四周学习总结 1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多数据库相关内容. 2. 书面作业 1. MySQL数据库 ...

  3. 201521123038 《Java程序设计》 第十四周学习总结

    201521123038 <Java程序设计> 第十四周学习总结 1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多数据库相关内容. 接口: DriverManager ...

  4. 201521123122 《java程序设计》第十四周学习总结

    ## 201521123122 <java程序设计>第十四周实验总结 ## 1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多数据库相关内容. 2. 书面作业 1. M ...

  5. 201771010134杨其菊《面向对象程序设计java》第九周学习总结

                                                                      第九周学习总结 第一部分:理论知识 异常.断言和调试.日志 1.捕获 ...

  6. 201871010132-张潇潇《面向对象程序设计(java)》第一周学习总结

    面向对象程序设计(Java) 博文正文开头 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cn ...

  7. 扎西平措 201571030332《面向对象程序设计 Java 》第一周学习总结

    <面向对象程序设计(java)>第一周学习总结 正文开头: 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 ...

  8. 201777010217-金云馨《面向对象程序设计Java》第四周总结学习

    2019面向对象程序设计(Java)第4周学习指导及要求 项目 内容 这个作业属于哪个课程 <任课教师博客主页链接>https://www.cnblogs.com/nwnu-daizh/ ...

  9. 汪慧和201771010123《面向对象程序设计JAVA》第四周实验总结

    第一部分:理论知识学习部分 1.类 类(class)是具有相同属性和行为的一组对象的集合,是构造程序的基本单元,是构造对象的模板或蓝图. 2.对象 对象:即数据,对象有三个特性——1.行为 2.状态 ...

  10. 201871010115——马北《面向对象程序设计JAVA》第二周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

随机推荐

  1. python程序在命令行执行提示ModuleNotFoundError: No module named 'XXX' 解决方法

    在ide中执行python程序,都已经在默认的项目路径中,所以直接执行是没有问题的.但是在cmd中执行程序,所在路径是python的搜索路径,如果涉及到import引用就会报类似ImportError ...

  2. Linux命令基础2-ls命令

    本文介绍的是linux中的ls命令,ls的单词是list files的缩写,意思的列出目录文件. 首先我们在admin用户的当前路径,新建一个test的文件夹,为了方便本文操作和介绍,创建了不同文件类 ...

  3. 纯粹的python绑定

    目前很多学习资料这样解释赋值与绑定,当是一个简单变量时,是赋值,当是复合变量时,是绑定. 注:赋值是重新复制变量到新变量中,赋值前后两个变量之间无联系.例C语言中: int a=6: int b: b ...

  4. LeetCode第一次刷题

    感觉自身编程水平还是差很多,所以刷刷题 LeetCode貌似是一个用的人比较多的题库,下面是第一题 给数组和目标和求需要元素的下标 public class Solution { public int ...

  5. 20155219 付颖卓《基于ARM试验箱的接口应用于测试》课程设计个人报告

    一.个人贡献 参与课设题目讨论及完成全过程: 资料收集: 负责代码调试: 修改小组结题报告: 负责试验箱的管理: 二.设计中遇到的问题及解决方法 1.makefile无法完成编译.如下图: 答:重新下 ...

  6. 微信小程序个人/企业开放服务类目一览表

    微信小程序个人/企业开放服务类目一览表   微信小程序个人开放服务类目表 服务类目 类目分类一 类目分类二 引导描述 出行与交通 代驾 / / 生活服务 家政.丽人.摄影/扩印.婚庆服务.环保回收/废 ...

  7. legend_noa 的 EMACS配置

    (defun my-c-mode-auto-pair() (interactive) (make-local-variable'skeleton-pair-alist) (setq skeleton- ...

  8. (转)Unity_什么是Draw Call? 什么是Batch?

    開發遊戲時,一定被時時提醒要減少 Draw Call,當然UNITY也不例外,打開Game Window裡的 Stats,可以看到 Draw Call 與 Batched 的數字.但到底甚麼是 Dra ...

  9. Google - Largest Sum Submatrix

    Given an NxN matrix of positive and negative integers, write code to find the submatrix with the lar ...

  10. docker 网络 路由

    通过在Docker宿主机上添加静态路由实现跨宿主机通信 模拟环境 主机1(192.168.58.144) 设置docker0 网关 (172.17.0.1/16)                主机2 ...