项目

内容

这个作业属于哪个课程

https://www.cnblogs.com/nwnu-daizh

这个作业的要求在哪里

https://www.cnblogs.com/nwnu-daizh/p/11995615.html

这个作业的目标是什么

  1. 掌握简单组件及其常用API
  2. 掌握对话框组件及其常用API
  3. 学习设计简单应运程序的GUI

第一部分  基础知识总结

(一)菜单

1.菜单创建

Swing菜单由菜单条(JMenuBar)、菜单(JMenu)和菜单项(JMenuItem)构成。菜单条是所有菜单和菜单项的根(容器)。

●创建一个菜单栏

JMenuBar menuBar=new JMenuBar();

●调用setJMenuBar方法将菜单栏添加到框架上

frame.setJMenuBar(menuBar);

●为每个菜单建立一个菜单对象

JMenu editMenu=new JMenu("Edit");

●将顶层菜单添加到菜单栏中

menuBar.add(editMenu);

●向菜单对象中添加菜单项,分隔符,子菜单

JMenuItem pasteItem=new JMenuItem("Paste");
deitMenu.add(pasteItem);
editMenu.
addSeparator();
JMenu optionsMenu=...; //子菜单
editMenu.add(optionsMenu);

2.菜单项中的图标

●利用JMenuItem(String.Icon)或JMenuItem(Icon)构造器为菜单指定一个图标,也可以利用JMenuItem类的setIcon方法(继承自AbstractButton类)指定一个图标

JMenuItem cutItem=new JMenuItem("Cut",new ImageIcon("cut.gif"));

3.复选框和单选按钮菜单项

●创建复选框菜单项的代码

JCheckBosMenuItem readonlyItem=new JCheckBoxMenuItem("Read-only");
optionsMenu.add(readonlyItem);

4.弹出菜单

创建

JPopupMenu popup=new JPopupMenu();

添加菜单项

JMenuItem item=new JMenuItem("Cut");
item.addActionListener(listener);
popup.add(item);

5.快捷键和加速器

●可以通过在菜单项的构造器中指定一个快捷字母来为菜单项设置快捷键

JMenuItem aboutItem=new JMenuItem("Aoubt",'A');

快捷键会自动显示在菜单项中,并带有一条下划线("About"),如果字母没有出现在菜单项标签字符串中,同样可以按下快捷键选择菜单项,只是快捷键没有显示出来

可以调用setDisplayedMnemonicIndex方法指定希望加下划线的字符

●只能在菜单项的构造器中设定快捷键字母,而不是菜单构造器中,如果想为菜单设置快捷键,需调用setMnemonic方法

JMenu helpMenu=new JMenu("Help");
helpMenu.setMnemonic('H');

●可以为菜单项添加加速器,加速器只能关联到菜单项上,加速器并不实际打开菜单,而是直接激活菜单关联的动作事件

openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));

6.启用和禁用菜单项

有些时候,某个特定的菜单项可能只能够在特定的环境下可用,例如,当文档以只读方式打开时,save菜单项就没有意义了

●启用或禁用菜单项需调用setEnabled方法

●启用和禁用菜单项有两个策略

①只要当文档以只读方式打开,就禁用save和save as

②在显示菜单之前禁用菜单项,这里必须为"menuselected"事件注册监听器

javax.swing.event包定义了MenuListener接口,包含3个方法

void menuSelected(MenuEvent event)
void menuDeselected(MenuEvent event)
void menuCanceled(MenuEvent event)

7.工具栏  JToolBar

工具栏只有位于采用边框布局或任何支持North,East,South,West约束布局管理器的容器内才可拖拽

将组件添加到工具栏中

JToolBar bar=new JToolBar();
bar.add(blueButton):

1.可以添加一个Action对象,从而添加一个指派动作的新JButton   2.可以用分隔符将按钮分组   3.将工具栏添加到框架中   4.为工具栏指定标题   5.垂直放置

8.工具提示

调用setToolText方法

如果使用Action对象,也可以用SHORT_DESCRIPTION关联工具提示

(二)对话框

1.选项对话框

[API]  javax.swing.JOptionPane

●JOptionPane有4个显示对话框的基本方法

showMessageDialog     //显示一条消息并等待用户点击OK

showConfirmDialog      //显示一条消息并等待用户确认(与OK/Cancel类似)

showOptionDialog        //显示一条消息并获得用户在一组选项中的选择

showInputDialog          //显示一条消息并获得用户输入的一行文本

(1)选择对话框的类型(消息、确认、选项或者输入)

(2)选择图标(错误、信息、警告、问题、无或者自定义)

(3)选择消息(字符串、图标、自定义组件或者它们的集合)

(4)对于确认对话框,选择选项类型(默认、Yes/No、Yes/No/Cancel或者OK/Cancel)

(5)对于选项对话框,选择选项(字符串、图表或者自定义组件)和默认选项

(6)对于输入对话框,选择文本框或者组合框

(7)调用JOptionPane API 中的相应方法

2.创建对话框

(1)在对话框构造器中,调用超类JDialog的构造器,需提供拥有者框架,对话框标题,特征

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

特征是指定对话框处于显示状态时,应用程序中其他窗口是否被锁住

(2)添加对话框的用户界面组件

(3)添加事件处理器

(4)设置对话框的大小

3.数据交换

[API]  javax.swing.SwingUtillities

[API]  javax.swing.JComponent

[API]  javax.swing.JRootPane

[API]  javax.swing.JButton

●对话框应提供设置默认数据的方法

●一旦设置了默认值,就可调用setVisible(true)让对话框显示在屏幕上

●点击OK/Cancel后,这两个按钮的事件处理器都会调用setVisible(false)终止显示

●希望知道用户是接收对话框还是取消对话框,在示例中设置了OK标志,在对话框显示之前是false,只有OK事件处理器可以设置为true

●示例中还包含另外一个改进,在构造一个JDialog对象时,需指定拥有者框架,但是,很多情况下,一个对话框可能有多个拥有者,所以最好准备显示对话框时再确认拥有者框架,一个技巧是让PasswordChoose扩展与JPanel,而不是JDialog

4.文件对话框

文件对话框  JFileChooser

●JFileChooser是一个模式对话框,但并不是JDialog类的子类

●需要调用showOpenDialog,而不是setVisible(true)显示打开文件的对话框,或调用showSaveDialog显示保存文件对话框

●接收文件的按钮自动标签为Open或Save,也可调用showDialog方法为按钮设定标签

(1)建立一个JFileChooser对象,与JDialog类的构造器不同,它不需要指定父组件,允许在多个框架中重用一个文件选择器

JFileChooser chooser=new JFileChooser();

(2)调用setCurrentDirectory方法设置当前目录

chooser.setCurrentDirectory(new File("."));

(3)如果有一个想要作为用户选择的默认文件名,可以使用setSelectedFile方法指定

chooser.setSelectedFile(new File(filename));

(4)如果允许用户选择多个文件,需调用setMultiSelectionEnabled方法

chooser.setMultiSelectionEnabled(true);

(5)如果想让对话框仅显示某一种类型的文件,需设置文件过滤器

●若想限制显示的文件,需创建一个实现了抽象类javax.swing.filechooser.FileFilter对象,文件选择器将每个文件传递给文件过滤器,只有文件过滤器接受的文件才被最终显示出来

●一旦有了文件过滤器对象,就可以调用JFileChooser类中的setFileFilter方法,将这个对象安装到文件选择器对象中

choose.setFileFilter(new FileNameExtensionFilter("Image files","gif","jpg");

●可以为一个文件选择器安装多个过滤器

chosser.addChoosableFileFilter(filter1);
chosser.addChoosableFileFilter(filter2);

●用户可以从文件对话框底部的组合框中选择过滤器,在默认情况下,All files过滤器总是显示在组合框中,然而,如果你想放弃All files过滤器,需调用

chooser.setAccrpyAllFileFilterUsed(false);

如果为加载和保存不同类型的文件重用一个文件选择器,就需调用

chooser.resetChoosableFilters()

这样可以在添加新文件过滤器之前清除旧文件过滤器

(6)在默认情况下,用户在文件选择器中只能选择文件,如果希望选择目录,需调用setFileSelectionMode方法,参数值为:JFileChoose.FILES_ONLY(默认值),JFileChooser.DIRECTORIES_ONLY或者JFileChooser.FILES_AND_DIRECTORIES

(7)调用showOpenDialog或showSaveDialog方法显示对话框,必须为这些调用提供父组件

int result=chooser.showOpenDialog(parent);
int result=chooser.showSaveDialog(parent);

●也可以调用showDialog方法,将一个显式文本传递给确认按钮

int result=chooser.showDialog(parent,"Select");

当且仅当用户确认、取消、离开对话框时才返回调用,返回值可以是JFileChooser.APPROVE_OPTION、JFileChooser.CANCEL_OPTION或者JFileChooser.ERROR_OPTION

(8)调用getSelectedFile()或getSelectedFiles()方法获取用户选择的一个或多个文件,这些方法将返回一个文件对象或一组文件对象,如需知道文件对象名,可以调用getPath方法

String filename=chooser.getSelectedFile().getPath();

5.颜色选择器

颜色选择器  JColorChooser

●利用颜色选择器显示模式对话框

Color selectedColor=JColorChooser.showDialog(parent,title,initialColor);

●也可以显示无模式颜色选择器对话框,需提供

  ■ 一个父组件

  ■ 对话框的标题

  ■ 选择模式/无模式对话框的标志

  ■ 颜色选择器

  ■ OK和Canel按钮的监听器(如果不需要可以设置为null)

●可以将颜色选择器组件直接添加到一个无模式对话框中

dialog=new JDialge(parent,false /*not modal */);
dialog.add(chooser);
dialog.pack()

第二部分  实验总结

2、实验内容和步骤

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

测试程序1

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

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

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

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); var fileMenu = new JMenu("File");//定义一个新的菜单为“File”
fileMenu.add(new TestAction("New"));//向'“File”里添加一个新的菜单项“New” // demonstrate accelerators var openItem = fileMenu.add(new TestAction("Open"));//向“File”添加一个“Open”菜单项
openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));//设置”Open“菜单项的点击等同于键盘输入"ctrl o" fileMenu.addSeparator();//向菜单添加分离符 saveAction = new TestAction("Save");
JMenuItem saveItem = fileMenu.add(saveAction);//向菜单添加保存菜单项
saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));//设置点击"Sava"按钮的效果等同于键盘输入"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);
}
}); var group = new ButtonGroup(); var insertItem = new JRadioButtonMenuItem("Insert");//复选框单选按钮名为"insert"
insertItem.setSelected(true);//设置菜单项的选项二状态(为ture表示选定)
var overtypeItem = new JRadioButtonMenuItem("Overtype");//复选框单选按钮名为"Overtype" group.add(insertItem);
group.add(overtypeItem); // demonstrate icons var cutAction = new TestAction("Cut");
cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
var copyAction = new TestAction("Copy");
copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif"));
var pasteAction = new TestAction("Paste");
pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif")); var editMenu = new JMenu("Edit");//构造一个"Eidt"菜单
editMenu.add(cutAction);//将cut添加到"Edit"菜单里
editMenu.add(copyAction);
editMenu.add(pasteAction); // demonstrate nested menus var optionMenu = new JMenu("Options"); optionMenu.add(readonlyItem);//添加read-only到Option里
optionMenu.addSeparator();//添加分隔符
optionMenu.add(insertItem);//添加单选按钮菜单项"insert"
optionMenu.add(overtypeItem); editMenu.addSeparator();//添加分隔符
editMenu.add(optionMenu);//将option添加到edit菜单 // demonstrate mnemonics var helpMenu = new JMenu("Help");//新建help菜单
helpMenu.setMnemonic('H');//设置Help等同于"H" var indexItem = new JMenuItem("Index");//构造一个"Index"菜单项
indexItem.setMnemonic('I');//设置"index"等同于"I"
helpMenu.add(indexItem);//添加"index"菜单项到help菜单里 // you can also add the mnemonic key to an action
var aboutAction = new TestAction("About");
aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));//设置"About"动作按钮等同于"A"
helpMenu.add(aboutAction);//添加"about"按钮到help里面 // add all top-level menus to menu bar var menuBar = new JMenuBar();
setJMenuBar(menuBar);//创建一个菜单栏 menuBar.add(fileMenu);//将File添加到菜单栏上
menuBar.add(editMenu);//将edit添加到菜单栏上
menuBar.add(helpMenu);//将help添加到菜单栏上 // demonstrate pop-ups popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction); var panel = new JPanel();
panel.setComponentPopupMenu(popup);
add(panel);
}
}
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(() -> {
var frame = new MenuFrame();
frame.setTitle("MenuTest");//设置文本标签名为“MenuTest”
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置窗口的关闭性
frame.setVisible(true);//设置可视性
});
}
}

实验输出结果截图为:

测试程序2

elipse IDE中调试运行教材517页程序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(() -> {
var frame = new ToolBarFrame();
frame.setTitle("ToolBarTest");//设置框架标签为"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);//添加到panel且居中 // set up actions var blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
var yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
Color.YELLOW);
var redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); var exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif"))
{
public void actionPerformed(ActionEvent event)
{
System.exit();//推迟项
}
};
exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit"); // populate toolbar var bar = new JToolBar();//构建一个新的工具栏
bar.add(blueAction);//添加前面定义好的blueAction
bar.add(yellowAction);
bar.add(redAction);
bar.addSeparator();//添加分离符
bar.add(exitAction);
add(bar, BorderLayout.NORTH);//添加到工具栏且置于北 // populate menu var menu = new JMenu("Color");//添加"color"菜单栏
menu.add(yellowAction);
menu.add(blueAction);
menu.add(redAction);
menu.add(exitAction);
var 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-1512-16,结合运行结果理解程序;

掌握选项对话框的用法。

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

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(() -> {
var frame = new OptionDialogFrame();//建立新的对话框
frame.setTitle("OptionDialogTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
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()
{
var 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 var showPanel = new JPanel();
var 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)
{
var g2 = (Graphics2D) g;
var 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(, );
}
}
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)
{
var button = new JRadioButton(option);
button.setActionCommand(option);
add(button);//添加按钮
group.add(button);
button.setSelected(option == options[]);
}
} /**
* Gets the currently selected option.
* @return the label of the currently selected radio button.
*/
public String getSelection()
{
return group.getSelection().getActionCommand();
}
}

实验输出结果截图为:(以以下三张截图为例)

测试程序4

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

掌握对话框的创建方法;

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

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(() -> {
var 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 var menuBar = new JMenuBar();
setJMenuBar(menuBar);
var fileMenu = new JMenu("File");
menuBar.add(fileMenu); // add About and Exit menu items // the About item shows the About dialog var 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 var 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 var ok = new JButton("OK");
ok.addActionListener(event -> setVisible(false)); // add OK button to southern border var panel = new JPanel();
panel.add(ok);
add(panel, BorderLayout.SOUTH); pack();
}
}

实验输出结果截图为:

测试程序5

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

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

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

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(() -> {
var 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 var mbar = new JMenuBar();
setJMenuBar(mbar);
var fileMenu = new JMenu("File");
mbar.add(fileMenu); // add Connect and Exit menu items var connectItem = new JMenuItem("Connect");
connectItem.addActionListener(new ConnectAction());
fileMenu.add(connectItem); // the Exit item exits the program var 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");
}
}
}
}
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 var mbar = new JMenuBar();
setJMenuBar(mbar);
var fileMenu = new JMenu("File");
mbar.add(fileMenu); // add Connect and Exit menu items var connectItem = new JMenuItem("Connect");
connectItem.addActionListener(new ConnectAction());
fileMenu.add(connectItem); // the Exit item exits the program var 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");
}
}
}
}
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

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

掌握文件对话框的用法;

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

package fileChooser;

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

import java.awt.*;
import javax.swing.*; /**
* @version 1.26 2018-04-10
* @author Cay Horstmann
*/
public class FileChooserTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
var frame = new ImageViewerFrame();
frame.setTitle("FileChooserTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
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(, ));
setBorder(BorderFactory.createEtchedBorder()); chooser.addPropertyChangeListener(event -> {
if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
{
// the user has selected a new file
File f = (File) event.getNewValue();
if (f == null)
{
setIcon(null);
return;
} // read the image into an icon
var icon = new ImageIcon(f.getPath()); // if the icon is too large to fit, scale it
if (icon.getIconWidth() > getWidth())
icon = new ImageIcon(icon.getImage().getScaledInstance(
getWidth(), -, 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 = ;
private static final int DEFAULT_HEIGHT = ;
private JLabel label;
private JFileChooser chooser; public ImageViewerFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // set up menu bar
var menuBar = new JMenuBar();
setJMenuBar(menuBar); var menu = new JMenu("File");
menuBar.add(menu); var openItem = new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(event -> {
chooser.setCurrentDirectory(new File(".")); // show file chooser dialog
int result = chooser.showOpenDialog(ImageViewerFrame.this); // if image file accepted, set it as icon of the label
if (result == JFileChooser.APPROVE_OPTION)
{
String name = chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(name));
pack();
}
}); var exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(event -> System.exit()); // use a label to display the images
label = new JLabel();
add(label); // set up file chooser
chooser = new JFileChooser(); // accept all image files ending with .jpg, .jpeg, .gif
var 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 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); // 添加颜色选择器面板到框架 ColorChooserPanel panel = new ColorChooserPanel();
add(panel);
}
}
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);
}
}
}
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);
});
}

实验输出结果截图为:

       

        

第三部分  实验心得

1.这周我们主要还是学习了Swing用户组件的知识,但是接触了相对更难的知识,当然也是在用户界面设计方面应运更加广泛的知识。也是会帮助我们完成更加功能复杂的设计。

2.菜单和对话框在我们平时的应运中是非常常见的,但是学习完这周的知识之后我才发现有关这方面的设计并非那么简单。尤其在完成老师留的结对编程设计作业的过程中会遇到更多的问题,心里想的和做出来的往往差距很大。当然,这还是源于自己学习到和真正感受到的知识太少,所以以后我会更加用心地学习。

201871010121-王方《面向对象程序设计JAVA》第十五周实验总结的更多相关文章

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

    一.理论部分 1.继承 如果两个类存在继承关系,则子类会自动继承父类的方法和变量,在子类中可以调用父类的方法和变量,如果想要在子类里面做一系列事情,应该放在父类无参构造器里面,在java中,只允许单继 ...

  2. 201771010123汪慧和《面向对象程序设计Java》第十三周实验总结

     一.理论部分 1.GUI为用户提供交互式的图形化操作界面. (1)提供了程序的外观和感觉.(2)程序利用图形用户界面接受用户的输入,向用户输出程序运行的结果. 2.Java有专门的类库生成各种标准图 ...

  3. 201771010123汪慧和《面向对象程序设计Java》第十一周实验总结

    一.理论部分 1.栈 (1)栈是一种特殊的线性表,是一种后进先出的结构.(2)栈是限定仅在表尾进行插入和删除运算的线性表,表尾称为栈顶,表头称为栈底.(3)栈的物理存储可以用顺序存储结构,也可以用链式 ...

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

    一.理论部分 1.接口 用interface声明,是抽象方法和常量值定义的集 合.从本质上讲,接口是一种特殊的抽象类. 在Java程序设计语言中,接口不是类,而是对类 的一组需求描述,由常量和一组抽象 ...

  5. 201771010123汪慧和《面向对象程序设计Java》第十七周实验总结

    一.理论部分 1.多线程并发执行中的问题 ◆多个线程相对执行的顺序是不确定的. ◆线程执行顺序的不确定性会产生执行结果的不确定性. ◆在多线程对共享数据操作时常常会产生这种不确定性. 2.线程的同步 ...

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

    一.理论部分: 1.继承 用已有类来构建新类的一种机制.当定义了一个新类继承了一个类时,这个新类就继承了这个类的方法和域,同时在新类中添加新的方法和域以适应新的情况. 2.类.超类.子类 (1)类继承 ...

  7. 20155322 2016-2017-2 《Java面向对象程序设计》第十二周课堂练习之Arrays和String单元测试

    20155322 2016-2017-2 <Java面向对象程序设计>第十二周课堂练习之Arrays和String单元测试 练习目地 在IDEA中以TDD的方式对String类和Array ...

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

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

  9. 20145209刘一阳《JAVA程序设计》第十五周补充测试

    第十五周补充测试 1.实验楼Linux中可以通过(ABC)查看用户登录情况. A .who B .who am i C .who mom likes D .who are you 2.在 Linux ...

  10. 201771010118马昕璐《面向对象程序设计java》第八周学习总结

    第一部分:理论知识学习部分 1.接口 在Java程序设计语言中,接口不是类,而是对类的一组需求描述,由常量和一组抽象方法组成.Java为了克服单继承的缺点,Java使用了接口,一个类可以实现一个或多个 ...

随机推荐

  1. Hyper-V与VirtualBox或VMware虚拟机软件冲突的解决方法(VirtualBox只能创建32位虚拟机)

    Hyper-V与VirtualBox或VMware虚拟机软件冲突的解决方法 Hyper-V是微软的虚拟化软件,功能类似VirtualBox.VMware,可以用来创建虚拟机. 虚拟化软件都是基于CPU ...

  2. [C1] Andrew Ng - AI For Everyone

    About this Course AI is not only for engineers. If you want your organization to become better at us ...

  3. CF812C Sagheer and Nubian Market

    CF812C Sagheer and Nubian Market 洛谷评测传送门 题目描述 On his trip to Luxor and Aswan, Sagheer went to a Nubi ...

  4. Python socket & socket server

    socket 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket(套接字). 建立网络通信连接至少要一对socket.socket是对TCP/IP的封装 使用方法 ...

  5. Vue 变异方法splice删除评论功能

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. python接口自动化3-发送post及其他请求

    前言 发过get请求相信学习post请求也很快学会,无非就是多了传参时的类型与参数格式.在我常见的post请求中用到最多的是json格式,但也有用其它,下面将介绍常用的参数类型格式. 一.Post请求 ...

  7. 【Linux命令】ulimit设置最大文件打开数

    一.简介 在Linux下有时会遇到Socket/File : Can't open so many files的问题.其实Linux是有文件句柄限制的,而且Linux默认一般都是1024(阿里云主机默 ...

  8. Appium移动自动化测试-----(三)Intellij IDEA + Android SDK + Genymotion Emulator

    下载安装Intellij IDEA 略 下载Android SDK http://tools.android-studio.org/index.php/sdk    下载后解压 http://www. ...

  9. 面试官:说说Mysql数据库分库分表,并且会有哪些问题?

    之前一篇文章已经谈到了数据库集群之主从集群也就是读写分离,也提到了读写分离其实只是分担了访问的压力,但是存储的压力没有解决. 存储的压力说白了就是随着系统的演化,需求的增加,可能表的数量会逐渐增多,比 ...

  10. 你必须知道的EF知识和经验(转)

    注意:以下内容如果没有特别申明,默认使用的EF6.0版本,code first模式. 推荐MiniProfiler插件 工欲善其事,必先利其器. 我们使用EF和在很大程度提高了开发速度,不过随之带来的 ...