实验十三 Swing图形界面组件(二)
实验时间 2019-12-6
第一部分:理论知识
A、菜单:
有两种类型的菜单:下拉式菜单和弹出式菜单。菜单与JComboBox和JCheckBox不同,它们在界面中是一直可见的。菜单与JComboBox的相同之处是每次只可选择一个项目。
在下拉式菜单或弹出式菜单中选择一个选项就产生一个ActionEvent事件。该事件被发送给那个选项的监视器,事件的意义由监视器解释。
菜单条、菜单和菜单项
下拉式菜单通过出现在菜单条上的名字可视化表示,菜单条(JMenuBar)通常出现在JFrame的顶部,一个菜单条显示多个下拉式菜单的名字。可以用两种方式来激活下拉式菜单。一种是按下鼠标的按钮,并保持按下状态,移动鼠标,直至释放鼠标完成选择,高亮度显示的菜单项即为所选择的。另一种方式是当光标位于菜单条中的菜单名上时,点击鼠标,在这种情况下,菜单会展开,且高亮度显示菜单项。
一个菜单条可以放多个菜单(JMenu),每个菜单又可以有许多菜单项(JMenuItem)。例如,Eclipse环境的菜单条有File、Edit、Source、Refactor等菜单,每个菜单又有许多菜单项。例如,File菜单有New、Open File、Close 、Close All等菜单项。
向窗口增设菜单的方法是:先创建一个菜单条对象,然后再创建若干菜单对象,把这些菜单对象放在菜单条里,再按要求为每个菜单对象添加菜单项。
菜单中的菜单项也可以是一个完整的菜单。由于菜单项又可以是另一个完整菜单,因此可以构造一个层次状菜单结构。
1.菜单条
类JMenuBar的实例就是菜单条。例如,以下代码创建菜单条对象menubar:
JMenuBar menubar = new JMenuBar();
在窗口中增设菜单条,必须使用JFrame类中的setJMenuBar()方法。例如,代码:
setJMenuBar(menubar);
类JMenuBar的常用方法有:
add(JMenu m):将菜单m加入到菜单条中。
countJMenus():获得菜单条中菜单条数。
getJMenu(int p):取得菜单条中的菜单。
remove(JMenu m):删除菜单条中的菜单m。
2. 菜单
由类JMenu创建的对象就是菜单。类JMenu的常用方法如下:
JMenu():建立一个空标题的菜单。
JMenu(String s):建立一个标题为s的菜单。
add(JMenuItem item):向菜单增加由参数item指定的菜单选项。
add(JMenu menu):向菜单增加由参数menu指定的菜单。实现在菜单嵌入子菜单。
addSeparator():在菜单选项之间画一条分隔线。
getItem(int n):得到指定索引处的菜单项。
getItemCount():得到菜单项数目。
insert(JMenuItem item,int n):在菜单的位置n插入菜单项item.
remove(int n):删除菜单位置n的菜单项
removeAll():删除菜单的所有菜单项。
3.菜单项
类JMenuItem 的实例就是菜单项。类JMenuItem的常用方法如下:
JMenuItem():构造无标题的菜单项。
JMenuItem(String s):构造有标题的菜单项。
setEnabled(boolean b):设置当前单项是否可被选择。
isEnabled():返回当前菜单项是否可被用户选择。
getLabel():得到菜单项的名称。
setLabel():设置菜单选项的名称。
addActionListener(ActionListener e):为菜单项设置监视器。监视器接受点击某个菜单的动作事件。
4. 处理菜单事件
菜单的事件源是用鼠标点击某个菜单项。处理该事件的接口是ActionListener,要实现的接口方法是actionPerformed(ActionEvent e),获得事件源的方法getSource().
【例 11-15】小应用程序示意窗口有菜单条的实现方法。设有一个按钮,当按钮处于打开窗口状态时,单击按钮将打开一个窗口,窗口设有一个菜单条,有两个菜单,每个菜单又各有三个菜单项。当一个菜单项被选中时,菜单项监视方法在文本框中显示相应菜单项被选中字样(查看源文件)。
5. 嵌入子菜单
创建了一个菜单,并创建多个菜单项,其中某个菜单项又是一个(含其他菜单项的)菜单,这就构成菜单嵌套。例如,将上述程序中的有关代码改成如下:
Menu menu1,menu2,item4;
MenuItem item3,item5,item6,item41,item42;
另插入以下代码创建item41和item42菜单项,并把它们加入到item4菜单中:
item41= new MenuItem(“东方红”);
item42 = new MenuItem(“牡丹”);
item4.add(item41);
item4.add(item42);
则点击item4菜单时,又会打开两个菜单项供选择。
6. 向菜单增加退出项
增设一个新的菜单项,对该菜单项加入监视,对应的监视方法中使用System.exit()方法,就能实现单击该菜单项时退出Java运行环境。例如,以下示意代码:
…
item7 = new MenuItem(“退出”);
item7.addActionListener(this);
…
public void actionPerformed(ActionEvent e){
if(e.getSource()==item7){
System.exit(0);
}
}
7.设置菜单项的快捷键
用MenuShortcut类为菜单项设置快捷键。构造方法是MenuShortcut(int key)。其中key可以取值KeyEvent.VK_A至KenEvent.VK_Z,也可以取 ‘a’到 ‘z’键码值。菜单项使用setShortcut(MenuShortcut k)方法来设置快捷键。例如,以下代码设置字母e为快捷键。
class Herwindow extends Frame implements ActionListener{
MenuBar menbar;
Menu menu;
MenuItem item;
MenuShortcut shortcut = new MenuShortcut(KeyEvent.VK_E);
…
item.setShortcut(shortcut);
…
}
B、对话框
Dialog 是一个带标题和边界的顶层窗口,边界一般用于从用户处获得某种形式的输入。 Dialog 的大小包括边界所指定的任何区域。边界区的维度可以使用 getInsets
方法获得,但是,由于这些维度是依赖于平台的,因此只有通过调用 pack
或 show
将 dialog 设置为可显示的,才能获得有效的 insets 值。由于 dialog 的总大小包括了边界区,因此边界有效地模糊了 dialog 的部分区域,约束了可用于在矩形中呈现或显示子部件的区域,矩形左上角的位置为(insets.left, insets.top)
,宽度为 width - (insets.left + insets.right)
,长度为 height - (insets.top + insets.bottom)
。
Dialog 的默认布局为 BorderLayout
。
Dialog 可以使用 setUndecorated
关闭本机装饰(例如 Frame & Titlebar)。只有在 dialog 不是 displayable
时才能完成此操作。
Dialog 在构造时必须有一个框架,或者将另一个 dialog 定义为它的所有者。当可见的 dialog 的所有者窗口被最小化时,dialog 会自动隐藏为对用户不可见。当所有者窗口被还原时,dialog 重新又变为用户可见的。
dialog 可以是无模式的(默认情况下)或有模式的。一个有模式的 dialog 将阻断输入到应用程序中其他所有顶层窗口的内容(将此 dialog 作为其所有者创建的窗口除外)。
Dialog 能够产生以下WindowEvents
:WindowOpened
、WindowClosing
、WindowClosed
、WindowActivated
、WindowDeactivated
、WindowGained
效果图如下:
第二部分:实验
1、实验目的与要求
(1) 掌握菜单组件用途及常用API;
(2) 掌握对话框组件用途及常用API;
(3) 学习设计简单应用程序的GUI。
2、实验内容和步骤
实验1: 导入第12章示例程序,测试程序并进行组内讨论。
测试程序1
l 在elipse IDE中调试运行教材512页程序12-8,结合运行结果理解程序;
l 掌握菜单的创建、菜单事件监听器、复选框和单选按钮菜单项、弹出菜单以及快捷键和加速器的用法。
l 记录示例代码阅读理解中存在的问题与疑惑。
12-8 代码:
package menu;
import java.awt.*;
import javax.swing.*;
/**
* @version 1.25 2018-04-10
* @author Cay Horstmann
*/
public class MenuTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
MenuFrame 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 = 300;
private static final int DEFAULT_HEIGHT = 200;
private Action saveAction;
private Action saveAsAction;
private JCheckBoxMenuItem readonlyItem;
private JPopupMenu popup;
/**
* A sample action that prints the action name to System.out.
*/
class TestAction extends AbstractAction
{
public TestAction(String name)
{
super(name);
}
public void actionPerformed(ActionEvent event)
{
System.out.println(getValue(Action.NAME) + " selected.");
}
}
public MenuFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
JMenu fileMenu = new JMenu("File");
fileMenu.add(new TestAction("New"));
// demonstrate accelerators
JMenuItem openItem = fileMenu.add(new TestAction("Open"));
openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
fileMenu.addSeparator();
saveAction = new TestAction("Save");
JMenuItem saveItem = fileMenu.add(saveAction);
saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
saveAsAction = new TestAction("Save As");
fileMenu.add(saveAsAction);
fileMenu.addSeparator();
fileMenu.add(new AbstractAction("Exit")
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
// demonstrate checkbox and radio button menus
readonlyItem = new JCheckBoxMenuItem("Read-only");
readonlyItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
boolean saveOk = !readonlyItem.isSelected();
saveAction.setEnabled(saveOk);
saveAsAction.setEnabled(saveOk);
}
});
ButtonGroup group = new ButtonGroup();
JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert");
insertItem.setSelected(true);
JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype");
group.add(insertItem);
group.add(overtypeItem);
// demonstrate icons
TestAction cutAction = new TestAction("Cut");
cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
TestAction copyAction = new TestAction("Copy");
copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif"));
TestAction 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
TestAction 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);
}
}
运行结果:
测试程序2
l 在elipse IDE中调试运行教材517页程序12-9,结合运行结果理解程序;
l 掌握工具栏和工具提示的用法;
l 记录示例代码阅读理解中存在的问题与疑惑。
12-9 代码:
package toolBar;
import java.awt.*;
import javax.swing.*;
/**
* @version 1.15 2018-04-10
* @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 = 300;
private static final int DEFAULT_HEIGHT = 200;
private JPanel panel;
public ToolBarFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add a panel for color change
panel = new JPanel();
add(panel, BorderLayout.CENTER);
// set up actions
ColorAction blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
ColorAction yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
Color.YELLOW);
ColorAction redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
AbstractAction exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif"))
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
};
exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");
// populate toolbar
JToolBar bar = new JToolBar();
bar.add(blueAction);
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);
}
}
}
其运行结果:
测试程序3
l 在elipse IDE中调试运行教材544页程序12-15、12-16,结合运行结果理解程序;
l 掌握选项对话框的用法。
l 记录示例代码阅读理解中存在的问题与疑惑。
代码如下:
package optionDialog;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.geom.Rectangle2D.Double;
import java.util.*;
import javax.swing.*;
/**
* A frame that contains settings for selecting various option dialogs.
*/
public class OptionDialogFrame extends JFrame
{
private ButtonPanel typePanel;
private ButtonPanel messagePanel;
private ButtonPanel messageTypePanel;
private ButtonPanel optionTypePanel;
private ButtonPanel optionsPanel;
private ButtonPanel inputPanel;
private String messageString = "Message";
private Icon messageIcon = new ImageIcon("blue-ball.gif");
private Object messageObject = new Date();
private Component messageComponent = new SampleComponent();
public OptionDialogFrame()
{
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(2, 3));
typePanel = new ButtonPanel("Type", "Message", "Confirm", "Option", "Input");
messageTypePanel = new ButtonPanel("Message Type", "ERROR_MESSAGE", "INFORMATION_MESSAGE",
"WARNING_MESSAGE", "QUESTION_MESSAGE", "PLAIN_MESSAGE");
messagePanel = new ButtonPanel("Message", "String", "Icon", "Component", "Other",
"Object[]");
optionTypePanel = new ButtonPanel("Confirm", "DEFAULT_OPTION", "YES_NO_OPTION",
"YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION");
optionsPanel = new ButtonPanel("Option", "String[]", "Icon[]", "Object[]");
inputPanel = new ButtonPanel("Input", "Text field", "Combo box");
gridPanel.add(typePanel);
gridPanel.add(messageTypePanel);
gridPanel.add(messagePanel);
gridPanel.add(optionTypePanel);
gridPanel.add(optionsPanel);
gridPanel.add(inputPanel);
// add a panel with a Show button
JPanel showPanel = new JPanel();
JButton showButton = new JButton("Show");
showButton.addActionListener(new ShowAction());
showPanel.add(showButton);
add(gridPanel, BorderLayout.CENTER);
add(showPanel, BorderLayout.SOUTH);
pack();
}
/**
* Gets the currently selected message.
* @return a string, icon, component, or object array, depending on the Message panel selection
*/
public Object getMessage()
{
String s = messagePanel.getSelection();
if (s.equals("String")) return messageString;
else if (s.equals("Icon")) return messageIcon;
else if (s.equals("Component")) return messageComponent;
else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
messageComponent, messageObject };
else if (s.equals("Other")) return messageObject;
else return null;
}
/**
* Gets the currently selected options.
* @return an array of strings, icons, or objects, depending on the Option panel selection
*/
public Object[] getOptions()
{
String s = optionsPanel.getSelection();
if (s.equals("String[]")) return new String[] { "Yellow", "Blue", "Red" };
else if (s.equals("Icon[]")) return new Icon[] { new ImageIcon("yellow-ball.gif"),
new ImageIcon("blue-ball.gif"), new ImageIcon("red-ball.gif") };
else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
messageComponent, messageObject };
else return null;
}
/**
* Gets the selected message or option type
* @param panel the Message Type or Confirm panel
* @return the selected XXX_MESSAGE or XXX_OPTION constant from the JOptionPane class
*/
public int getType(ButtonPanel panel)
{
String s = panel.getSelection();
try
{
return JOptionPane.class.getField(s).getInt(null);
}
catch (Exception e)
{
return -1;
}
}
/**
* The action listener for the Show button shows a Confirm, Input, Message, or Option dialog
* depending on the Type panel selection.
*/
private class ShowAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (typePanel.getSelection().equals("Confirm")) JOptionPane.showConfirmDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel));
else if (typePanel.getSelection().equals("Input"))
{
if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
else JOptionPane.showInputDialog(OptionDialogFrame.this, getMessage(), "Title",
getType(messageTypePanel), null, new String[] { "Yellow", "Blue", "Red" },
"Blue");
}
else if (typePanel.getSelection().equals("Message")) JOptionPane.showMessageDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
else if (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel), null, getOptions(), getOptions()[0]);
}
}
}
/**
* A component with a painted surface
*/
class SampleComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Double rect = new Rectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1);
g2.setPaint(Color.YELLOW);
g2.fill(rect);
g2.setPaint(Color.BLUE);
g2.draw(rect);
}
public Dimension getPreferredSize()
{
return new Dimension(10, 10);
}
}
package optionDialog;
import java.awt.*;
import javax.swing.*;
/**
* @version 1.35 2018-04-10
* @author Cay Horstmann
*/
public class OptionDialogTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
OptionDialogFrame 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 button = new JRadioButton(option);
button.setActionCommand(option);
add(button);
group.add(button);
button.setSelected(option == options[0]);
}
}
/**
* Gets the currently selected option.
* @return the label of the currently selected radio button.
*/
public String getSelection()
{
return group.getSelection().getActionCommand();
}
}
程序的运行结果:
测试程序4
l 在elipse IDE中调试运行教材552页程序12-17、12-18,结合运行结果理解程序;
l 掌握对话框的创建方法;
l 记录示例代码阅读理解中存在的问题与疑惑。
代码如下:
package dialog;
import java.awt.*;
import javax.swing.*;
/**
* @version 1.35 2018-04-10
* @author Cay Horstmann
*/
public class DialogTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
DialogFrame 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 = 300;
private static final int DEFAULT_HEIGHT = 200;
private AboutDialog dialog;
public DialogFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// construct a File menu
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
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(0));
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(
"Core Java
By Cay Horstmann"),
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();
}
}
运行结果:
测试程序5
l 在elipse IDE中调试运行教材556页程序12-19、12-20,结合运行结果理解程序;
l 掌握对话框的数据交换用法;
l 记录示例代码阅读理解中存在的问题与疑惑。
代码如下:
package dataExchange;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* A frame with a menu whose File->Connect action shows a password dialog.
*/
public class DataExchangeFrame extends JFrame
{
public static final int TEXT_ROWS = 20;
public static final int TEXT_COLUMNS = 40;
private PasswordChooser dialog = null;
private JTextArea textArea;
public DataExchangeFrame()
{
// construct a File menu
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File");
mbar.add(fileMenu);
// add Connect and Exit menu items
JMenuItem connectItem = new JMenuItem("Connect");
connectItem.addActionListener(new ConnectAction());
fileMenu.add(connectItem);
// the Exit item exits the program
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(event -> System.exit(0));
fileMenu.add(exitItem);
textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
add(new JScrollPane(textArea), BorderLayout.CENTER);
pack();
}
/**
* The Connect action pops up the password dialog.
*/
private class ConnectAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// if first time, construct dialog
if (dialog == null) dialog = new PasswordChooser();
// set default values
dialog.setUser(new User("yourname", null));
// pop up dialog
if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
{
// if accepted, retrieve user input
User u = dialog.getUser();
textArea.append("user name = " + u.getName() + ", password = "
+ (new String(u.getPassword())) + "\n");
}
}
}
}
package dataExchange;
import java.awt.*;
import javax.swing.*;
/**
* @version 1.35 2018-04-10
* @author Cay Horstmann
*/
public class DataExchangeTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
DataExchangeFrame frame = new DataExchangeFrame();
frame.setTitle("DataExchangeTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package dataExchange;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Frame;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
/**
* A password chooser that is shown inside a dialog.
*/
public class PasswordChooser extends JPanel
{
private JTextField username;
private JPasswordField password;
private JButton okButton;
private boolean ok;
private JDialog dialog;
public PasswordChooser()
{
setLayout(new BorderLayout());
// construct a panel with user name and password fields
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 2));
panel.add(new JLabel("User name:"));
panel.add(username = new JTextField(""));
panel.add(new JLabel("Password:"));
panel.add(password = new JPasswordField(""));
add(panel, BorderLayout.CENTER);
// create Ok and Cancel buttons that terminate the dialog
okButton = new JButton("Ok");
okButton.addActionListener(event -> {
ok = true;
dialog.setVisible(false);
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(event -> dialog.setVisible(false));
// add buttons to southern border
JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
add(buttonPanel, BorderLayout.SOUTH);
}
/**
* Sets the dialog defaults.
* @param u the default user information
*/
public void setUser(User u)
{
username.setText(u.getName());
}
/**
* Gets the dialog entries.
* @return a User object whose state represents the dialog entries
*/
public User getUser()
{
return new User(username.getText(), password.getPassword());
}
/**
* Show the chooser panel in a dialog.
* @param parent a component in the owner frame or null
* @param title the dialog window title
*/
public boolean showDialog(Component parent, String title)
{
ok = false;
// locate the owner frame
Frame owner = null;
if (parent instanceof Frame)
owner = (Frame) parent;
else
owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
// if first time, or if owner has changed, make new dialog
if (dialog == null || dialog.getOwner() != owner)
{
dialog = new JDialog(owner, true);
dialog.add(this);
dialog.getRootPane().setDefaultButton(okButton);
dialog.pack();
}
// set title and show dialog
dialog.setTitle(title);
dialog.setVisible(true);
return ok;
}
}
package dataExchange;
/**
* A user has a name and password. For security reasons, the password is stored as a char[], not a
* String.
*/
public class User
{
private String name;
private char[] password;
public User(String aName, char[] aPassword)
{
name = aName;
password = aPassword;
}
public String getName()
{
return name;
}
public char[] getPassword()
{
return password;
}
public void setName(String aName)
{
name = aName;
}
public void setPassword(char[] aPassword)
{
password = aPassword;
}
}
程序的运行结果:
测试程序6
l 在elipse IDE中调试运行教材564页程序12-21、12-22、12-23,结合程序运行结果理解程序;
l 掌握文件对话框的用法;
l 记录示例代码阅读理解中存在的问题与疑惑。
代码如下:
package fileChooser;
import java.awt.*;
import java.io.*;
import javax.swing.*;
/**
* A file chooser accessory that previews images.
*/
public class ImagePreviewer extends JLabel
{
/**
* Constructs an ImagePreviewer.
* @param chooser the file chooser whose property changes trigger an image
* change in this previewer
*/
public ImagePreviewer(JFileChooser chooser)
{
setPreferredSize(new Dimension(100, 100));
setBorder(BorderFactory.createEtchedBorder());
chooser.addPropertyChangeListener(event -> {
if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
{
// 用户选择一个新文件
File f = (File) event.getNewValue();
if (f == null)
{
setIcon(null);
return;
}
// 将影像读取成图示
ImageIcon icon = new ImageIcon(f.getPath());
// 如果图标太大,无法安装,请缩放
if (icon.getIconWidth() > getWidth())
icon = new ImageIcon(icon.getImage().getScaledInstance(
getWidth(), -1, Image.SCALE_DEFAULT));
setIcon(icon);
}
});
}
}
package fileChooser;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.filechooser.FileFilter;
/**
* A frame that has a menu for loading an image and a display area for the
* loaded image.
*/
public class ImageViewerFrame extends JFrame
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 400;
private JLabel label;
private JFileChooser chooser;
public ImageViewerFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// 设置菜单栏
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem openItem = new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(event -> {
chooser.setCurrentDirectory(new File("."));
// 显示文件选择器对话框
int result = chooser.showOpenDialog(ImageViewerFrame.this);
// 如果图像文件被接受,将其设置为标签的图标
if (result == JFileChooser.APPROVE_OPTION)
{
String name = chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(name));
pack();
}
});
JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(event -> System.exit(0));
// 使用标签显示影像
label = new JLabel();
add(label);
//设置文件选择器
chooser = new JFileChooser();
// 接受所有以之结尾的影像档案。JPG。杰伯图形交换格式
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Image files", "jpg", "jpeg", "gif");
chooser.setFileFilter(filter);
chooser.setAccessory(new ImagePreviewer(chooser));
chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif")));
}
}
package fileChooser;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.filechooser.FileFilter;
/**
* A file view that displays an icon for all files that match a file filter.
*/
public class FileIconView extends FileView
{
private FileFilter filter;
private Icon icon;
/**
* Constructs a FileIconView.
* @param aFilter a file filter--all files that this filter accepts will be shown
* with the icon.
* @param anIcon--the icon shown with all accepted files.
*/
public FileIconView(FileFilter aFilter, Icon anIcon)
{
filter = aFilter;
icon = anIcon;
}
public Icon getIcon(File f)
{
if (!f.isDirectory() && filter.accept(f)) return icon;
else return null;
}
}
package fileChooser;
import java.awt.*;
import javax.swing.*;
/**
* @version 1.26 2018-04-10
* @author Cay Horstmann
*/
public class FileChooserTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
ImageViewerFrame frame = new ImageViewerFrame();
frame.setTitle("FileChooserTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
程序的运行结果如下:
测试程序7
l 在elipse IDE中调试运行教材570页程序12-24,结合运行结果理解程序;
l 了解颜色选择器的用法。
l 记录示例代码阅读理解中存在的问题与疑惑。
代码如下:
package colorChooser;
import javax.swing.*;
/**
* A frame with a color chooser panel
*/
public class ColorChooserFrame extends JFrame
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public ColorChooserFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// 添加颜色选择器面板到框架
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);
});
}
}
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);
}
}
}
其运行结果:
第三部分:实验总结
老师在上一周的的基础上,又讲了与菜单、对话框相关的内容。在实验课上,对一部分代码进行了运行,测试代码是我发现菜单的类型有两种类型的菜单:下拉式菜单和弹出式菜单。其次就是对话框了,对话框有文件对话框,消息对话框,输入对话框,确认对话框以及颜色对话框。在实验过程中,请教了老师实验时一再出现的问题,通过老师的讲解,我对一些问题有了解决办法,在课堂上我做了笔记,以防下次再出现这样的状况。