201871010107-公海瑜《面向对象程序设计(java)》第十五周学习总结

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

(1) 掌握菜单组件用途及常用API;

(2) 掌握对话框组件用途及常用API;

(3) 学习设计简单应用程序的GUI。

第一部分:总结菜单、对话框两类组件用途及常用API

1.菜单

菜单是GUI编程中经常用到的一种组件。位于窗口顶部的菜单栏(menu bar)中包括下拉菜单的名字。点击一个名字就可以打开包含菜单项(menu items)和子菜单(submenus)的菜单。

分为JMenuBar/JMenu/JMenuItem,当选择菜单项时会触发一个动作事件,需要注册监听器监听。

菜单的创建

首先创建一个菜单栏菜单栏是一个可以添加到容器组件任何位置的组件。通常放置在框架的顶部。

JMenuBar menuBar=new JMenuBar();

调用框架的setJMenuBar方法可将一个菜单栏对象添加到框架上

  frame.setJMenuBar(menuBar);
 
 创建菜单对象,并将菜单对象添加到菜单栏中
  JMenu editMenu=new Jmenu("Edit");
  menuBar.add(editMenu);
 
 加速器可以在不打开菜单的情况下选中菜单项的快捷键。 例如,很多应用程序把CTRL + O和CTRL + S关联到菜单中的Open和Save项。

2.对话框

对话框是一种大小不能变化、不能有菜单的容器窗口;

对话框不能作为一个应用程序的主框架,而必须包含在其他的容器中。

对话框分为模式对话框和无模对话框,模式对话框就是未处理此对话框之前不允许与其他窗口交互。

 JOptionPane提供的对话框是模式对话框。当模式对话框显示时,它不允许用户输入到程序的其他的窗口。使用JOptionPane,可以创建和自定义问题、信息、警告和错误等几种类型的对话框。

创建对话框,要想实现一个对角框,需要从JDialog派生一个类。这与应用程序窗口派生与JFrame的过程完全一样。具体过程如下:

(1)JOptionPane

提供了四个用静态方法(showxxxx)显示的对话框:

构造对话框的步骤:

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

2)选择消息类型(String/Icon/Component/Object[]/任何其他对象)

3)选择图标(ERROR_MESSAGE/INFORMATION_MESSAGE/WARNING_MESSAGE/QUESTION_MESSAGE/PLAIN_MESSAGE)

4)对于确认对话框,选择按钮类型(DEFAULT_OPTION/YES_NO_OPTION/YES_NO_CANCEL_OPTION/OK_CANCEL_OPTION)

5)对于选项对话框,选择选项(String/Icon/Component)

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

确认对话框和选择对话框调用后会返回按钮值或被选的选项的索引值

(2)JDialog类

可以自己创建对话框,需调用超类JDialog类的构造器

public aboutD extends JDialog
{
public aboutD(JFrame owner)
{
super(owner,"About Text",true);
....
}
}
构造JDialog类后需要setVisible才能时窗口可见

if(dialog == null)
dialog = new JDialog();
dialog.setVisible(true);

(3)文件对话框(JFileChooser类)

专门用于对文件(或目录)进行浏览和选择的对话框,常用的构造方法:

JFileChooser():根据用户的缺省目录创建文件对话框

JFileChooser(File currentDirectory):根据File型参数currentDirectory指定的目录创建文件对话框

JFileChooser(String currentDirectoryPath):根据String型参数currentDirector

(4)颜色对话框(JColorChooser类)

Swing提供了JColorChooser来选取颜色。与JFileChooser一样,颜色选择器也是一个组件,而不是一个对话框,但是它包含了用于创建包含颜色的选择器组件的对话框方法。

第二部分:实验部分

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

测试程序1

elipse IDE中调试运行教材512页程序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(() -> {
var frame = new MenuFrame();
frame.setTitle("MenuTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package menu;

import java.awt.event.*;
import javax.swing.*; /**
* 一个带有示例菜单栏的框架。
*/
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; /**
* 将动作名称打印到Studio.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");
fileMenu.add(new TestAction("New")); // 演示加速器 var 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();
}
}); // 演示复选框和单选按钮菜单 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");
insertItem.setSelected(true);
var overtypeItem = new JRadioButtonMenuItem("Overtype"); group.add(insertItem);
group.add(overtypeItem); // 演示图标 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");
editMenu.add(cutAction);
editMenu.add(copyAction);
editMenu.add(pasteAction); // 演示嵌套菜单 var optionMenu = new JMenu("Options"); optionMenu.add(readonlyItem);
optionMenu.addSeparator();
optionMenu.add(insertItem);
optionMenu.add(overtypeItem); editMenu.addSeparator();
editMenu.add(optionMenu); // 助记符演示 var helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H'); var indexItem = new JMenuItem("Index");
indexItem.setMnemonic('I');
helpMenu.add(indexItem); // 还可以将助记键添加到动作中。
var aboutAction = new TestAction("About");
aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));
helpMenu.add(aboutAction); // 将所有顶级菜单添加到菜单栏 var menuBar = new JMenuBar();
setJMenuBar(menuBar); menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu); // 演示弹出窗口 popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction); var panel = new JPanel();
panel.setComponentPopupMenu(popup);
add(panel);
}
}

运行结果:

测试程序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");
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(); //创建新的JPanel
add(panel, BorderLayout.CENTER); //建立动作 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); //用Action对象填充工具栏
bar.add(yellowAction);
bar.add(redAction);
bar.addSeparator(); //用分隔符将按钮分组
bar.add(exitAction);
add(bar, BorderLayout.NORTH); // populate menu var menu = new JMenu("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

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

运行截图:

测试程序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.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 var panel = new JPanel();
panel.setLayout(new GridLayout(, ));
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);
}); var cancelButton = new JButton("Cancel");
cancelButton.addActionListener(event -> dialog.setVisible(false)); // add buttons to southern border var 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

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

掌握文件对话框的用法;

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

程序代码:

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

import java.awt.*;
import java.io.*; import javax.swing.*; /**
* A file chooser accessory that previews images.
*/
public class ImagePreviewer extends JLabel
{
/**
* Constructs an ImagePreviewer.
* @param chooser the file chooser whose property changes trigger an image
* change in this previewer
*/
public ImagePreviewer(JFileChooser chooser)
{
setPreferredSize(new Dimension(, ));
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")));
}
}

运行结果:

测试程序7

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

了解颜色选择器的用法。

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

程序代码:

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

运行结果:

实验总结:

        上周继续学习了有关Swing用户界面组件的相关知识,对菜单、对话框等的运用有了一定的了解以及一些常用的API。课后通过实验实例更深入地了解了相关知识,做到了理论知识和实际应用相结合,但总体上来说有些方面还是不太懂,需要自己下去好好下功夫。

201871010107-公海瑜《面向对象程序设计(java)》第十五周学习总结的更多相关文章

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

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

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

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

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

    第八周学习总结 第一部分:理论知识 一.接口.lambda和内部类:  Comparator与comparable接口: 1.comparable接口的方法是compareTo,只有一个参数:comp ...

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

    第七周学习总结 第一部分:理论知识 1.继承是面向对象程序设计(Object Oriented Programming-OOP)中软件重用的关键技术.继承机制使用已经定义的类作为基础建立新的类定义,新 ...

  5. 201871010126 王亚涛《面向对象程序设计 JAVA》 第十三周学习总结

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

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

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

  7. 201871010126 王亚涛 《面向对象程序设计 (Java)》第十七周学习总结

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

  8. 马凯军201771010116《面向对象程序设计Java》第八周学习总结

    一,理论知识学习部分 6.1.1 接口概念 两种含义:一,Java接口,Java语言中存在的结构,有特定的语法和结构:二,一个类所具有的方法的特征集合,是一种逻辑上的抽象.前者叫做“Java接口”,后 ...

  9. 周强201771010141《面向对象程序设计Java》第八周学习总结

    一.理论知识学习部分 Java为了克服单继承的缺点,Java使用了接口,一个类可以实现一个或多个接口. 接口体中包含常量定义和方法定义,接口中只进行方法的声明,不提供方法的实现. 类似建立类的继承关系 ...

随机推荐

  1. [mybatis] sql语句无错误,但是执行多条sql语句时,抛出java.sql.SQLSyntaxErrorException

    错误内容 org.springframework.jdbc.BadSqlGrammarException: ### Error updating database. Cause: java.sql.S ...

  2. win10 去除快捷方式小箭头

    @echo off color 2 reg delete HKCR\lnkfile /v IsShortcut /f reg delete HKCR\piffile /v IsShortcut /f ...

  3. Note | 论文写作笔记

    目录 1. 规范 2. 语法 3. 其他 4. 好图好表 5. 好表达 我们的工作很重要 我们的工作有意义 我们的工作细节 我们怎么组织这篇文章 最终效果出类拔萃 怎么解释我们的成功 写完逐条核对吧. ...

  4. leetcode 410. 分割数组的最大值(二分法)

    1. 题目描述 给定一个非负整数数组和一个整数 m,你需要将这个数组分成 m 个非空的连续子数组.设计一个算法使得这 m 个子数组各自和的最大值最小. 注意: 数组长度 n 满足以下条件: 1 ≤ n ...

  5. LCT好题总结

    写在前面: 初探多项式之后,开始了数据结构之旅,可持久化数据结构的总结大概是咕了,只总结一些$LCT$的题 T1:水管局长数据加强版 发现题中只有删边操作,而我们只会做加边,所有考虑时光倒流 先在最后 ...

  6. redis.windows.conf 配置注释

    . daemonize no Redis默认不是以守护进程的方式运行,可以通过该配置项修改,使用yes启用守护进程 . pidfile /var/run/redis_6379.pid 当Redis以守 ...

  7. python运维开发常用模块(6)发送电子邮件模块smtplib

    1.模块常用方法 SMTP类定义:smtplib.SMTP([host[,port[,local_hostname[, timeout]]]]),作为SMTP的构造函数,功能是与smtp服务器建立连接 ...

  8. FFmpeg 是什么?

    笔者才开始学习音视频开发,主要是通过阅读刘歧.赵文杰编著的<FFmpeg从入门到精通>以及雷霄骅博士博客总结写的入门心得体会. 官方文档资料 FFmpeg官方文档:https://ffmp ...

  9. CSS3 clip裁剪动画

    CSS3 clip裁剪动画 下面是比较简单的例子 <pre><html><head><style type="text/css">i ...

  10. SpringDataRedis入门Demo

    步骤: 约定>配置>代码 在pom.xml中导入依赖(redis和jedis以及其他所需的依赖) > 配置相关配置文件(redis-config.properties 和applic ...