正文开头:

项目

内容

这个作业属于哪个课程

https://home.cnblogs.com/u/nwnu-daizh/

这个作业的要求在哪里

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

作业学习目标

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

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

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

正文内容:

第一部分:总结第十二章理论知识

  菜单

    1.创建菜单栏:可以添加到容器组件的任何位置,通常在框架的顶部           

        eg:JMenuBar menuBar = new JMenuBar()      

    2.添加到框架:            

         frame.setJMenuBar(menuBar);      

    3.创建菜单对象,并将对象添加到菜单栏中

 JMenu editMenu=new JMenu("Edit");
         menuBar.add(editMenu);
    向菜单对象添加菜单项
         JMenuItem pasteItem=new JMenuItem();

         editMenu.add(pasteItem);

    添加分隔符
         editMenu.addSeparator();

    向对象添加子菜单:
         JMenu optionsMenu=new Jmenu("option");
         editMenu.add(optionsMenu);

    监听器

      用户选择菜单时,触发一个动作,需要安装一个动作监听器

         ActionListener listener=...;

         pasteItem.addActionListener(listener);

      菜单对象的add方法可返回创建的子菜单项。可以用下列方法获得她,并添加监听器:

         JMenuItem pasteItem =editMenu.add("Paste");

         pasteItem.addActionListener(listener);

    弹出菜单JpopMenu

       创建弹出菜单:JpopMenu popup=new JpopMenu();弹出菜单没有标题

       添加菜单项:JMenuItem item = new JMenuItem("Cut");

             item.addActionListener(listener);

             popup.add(item);

       弹出菜单用show才能显示:popup.show(panel,x,y);

       弹出式触发器:用户点击鼠标的某个键时弹出菜单

          调用方法设置弹出式触发器:component.setComponentPopMenu(popup);

    快捷键

        eg:JMenuItem CutItem = new JMenuItem("Index");

         CutItem.setMnemonic("|");快捷键下有一条下划线

    加速器

      使用setAccelerator方法可以将加速器关联到一个菜单项。

      eg:openItem.setAccelerator(KeyStroke.getKeyStrock("ctrl o"));

        菜单项并不打开菜单,而是直接激活菜单关联的动作事件
    启用或禁用菜单项

      1.屏蔽/启用菜单项的方法:

        aMenuItem.setEnabled(boolean);

          boolean为false时,屏蔽;为true时,启用

      2.动态启用/屏蔽某菜单项,需要为菜单项注册“menuSelectd"事件监听器

    工具栏JToolBar(可以移动,拖拽)

       优点:可以移动,脱离菜单栏或拖拽到框架其他地方

       工具提示:某个按钮的含义

             setToolTest方法添加工具提示到JComponent;

             exitButton.setToolTipText("Exit");

        另一种方法就是,如果使用Action对象,就可以用SHORT-DESCRIPTION关联工具提示
  对话框

    1.对话框:大小不能变,不能有菜单的容器窗口

         不可以作为应用程序的主框架,必须包含在其他容器中

      多种形式的对话框:

        JOptionPane:支持简单,标准的对话框

        JFileChooser:支持文件打开,保存对话框

        ProgressMonitor:支持操作动作条控制对话框

      对话框依赖框架

      对话框分为无模式和有模式两种

          有模式:处于激活状态时,程序只能响应对话框内部的事件,不能再激活依赖的窗口或组件,且将堵塞当前线程的执行,即堵        塞使得对话框处于激活状态的线程,直到该对话框消失不可见;

          无模式:处于激活状态时,程序仍能激活它所依赖的窗口或者组件,不能堵塞线程的执行。

   2.选项对话框:

    (1)JOptionPane提供的对话框是模式对话框,可以创建和对定义问题、信息、警告、和错误等几种类型的对话框。

    (2)JOptionPane类:定义了多个showXxxDiaglog形式的静态方法

      showMessageDialog信息对话框

      showConfirmDiaglog确认对话框

      showOptionDialog选项对话框

      showInputDialog输入对话框

        showXxxDiaglo的方法参数:Component parentCopmonent

                    Object message

                    String title

                    int messageType

    (3)创建对话框:

          JDialog  (Frame owner) 没有标题的非模式对话框

          JDialog(Frame owner ,boolean modal) 没有标题的对话框

          JDialog(Frame owner ,String title)  有标题的非模式对话框

          JDialog(Frame owner ,String title,boolean modal)有标题的对话框。

    

第二部分:实验部分

 实验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(() -> {
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//菜单项触发命令,通常采用扩展抽象类AbstractAction来定义一个实现Action接口的类
{
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"));//添加菜单项open
openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));//快捷键,与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);//启用或禁用菜单选项利用setEnabled方法
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
var 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

    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(() -> {
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)//重写actionPerformed方法
{
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(() -> {
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)//for-each循环打印
{
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();
}
}

  

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//继承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(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 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 -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));//若typePanel中选择Confirm按钮,得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)
{
var g2 = (Graphics2D) g;
var 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);
}
}

结果:

  测试程序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(() -> {
DialogFrame frame = new DialogFrame();
frame.setTitle("DialogTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
package dialog;

import java.awt.BorderLayout;

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

  

结果:

  测试程序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;

/**
* 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;
}
}
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;//ok是boolean型的
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(2, 2));//网格布局,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);
}); var cancelButton = new JButton("Cancel");
cancelButton.addActionListener(event -> dialog.setVisible(false));//调用取消按钮的添加监听器,设置组件不可见 // add buttons to southern border var buttonPanel = new JPanel();
buttonPanel.add(okButton);//加OK按钮
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;

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 var mbar = new JMenuBar();
setJMenuBar(mbar);
var fileMenu = new JMenu("File");
mbar.add(fileMenu); // add Connect and Exit menu items加入Connect和Exit 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(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");
}
}
}
}

  结果:

  测试程序6

    在elipse IDE中调试运行教材556页程序12-21、12-2212-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)//getIcon获得文件类型的图标
{
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(100, 100));//setPreferredSize在布局管理器会获取空间的PreferredSize
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(), -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); // 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("."));//用setCurrentDirectory改变进程的当前目录 // show file chooser dialog
int result = chooser.showOpenDialog(ImageViewerFrame.this);//(不太理解)用showOpenDialog方法,显示打开文件的对话框 // 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(0)); // 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 接受以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.*;
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 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.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()),//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);
}
}
}

  

结果:

实验总结:     

    通过本次的实验,我初步学习到了菜单组件和对话框组件用途及常用的应用编程接口并且练习设计了简单应用程序的GUI,对于本次实验,导入程序相对较难理解,必须要整体把握设计流程才能更好的理解本次程序,但是通过课后学习,阅读代码并注释,对菜单的学习有了更深的理解。

 

201871010109-胡欢欢 《面向对象程序设计(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使用了接口,一个类可以实现一个或多个接口. 接口体中包含常量定义和方法定义,接口中只进行方法的声明,不提供方法的实现. 类似建立类的继承关系 ...

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

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

随机推荐

  1. jquery和bootstrap:

    事件:绑定bind和解绑unbind:  $('选择器').bind('事件',function(){  // 操作 ​ }) ​ $('选择器').unbind('事件') ​ $('选择器').c ...

  2. Open3D-PointNet2-Semantic3D-master的运行

    1.修改download_semantic3d.sh文件 #!/bin/bash ans=`dpkg-query -W p7zip-full` if [ -z "$ans" ]; ...

  3. JAVA 中加载属性文件的4种方法

    小总结 : 这个集合属性可以反序列化, 把持久化数据读出来, 输入流中放入要操作的文件! p.load加载这个输入流! p.getProperty( key) 根据这个键获得值! 补充 : web工程 ...

  4. sqlserver deadlock

    当时系统测试的时候,由于使用了自动化测试跑脚本,一下子出了很多sqlserver deadlock的问题. 都处于system test阶段了,哪儿还有时间仔细分析这些死锁是怎么出来的,直接上retr ...

  5. backbone 路由传参(可选)

    因为维护公司的老项目而接触到backbone.以前是只闻其名,未见其码. 因为其他项目需要跳转到本项目的某个页面,但是需要UI改变. 考虑的方法是给路由添加一个可选参数.代码如下: 正常路由: rou ...

  6. 【转】在cmd/bat脚本中获取当前脚本文件所在目录

    一.关于cd的/d参数 关于cd 的/d参数,在cmd中敲入cd /?可以看到/d参数的解释如下: 使用 /D 命令行开关,除了改变驱动器的当前目录之外,还可改变当前驱动器.这句话不太好理解,我做个试 ...

  7. NPOI 帮助类

    NPOI 帮助类 代码实现了来自于互联网 using System; using System.Data; using System.IO; using System.Text; using NPOI ...

  8. 解决基于TypeScript 的 RN项目相对路径引入组件的问题

    一.前言 在开发RN项目时,经常会要使用这样的方式(../../../)来引入组件,感觉非常繁琐,如果项目结构层级比较多,引入的头部更加分不清. 那有没有一种方案和vue项目一样,经过配置后简写路径, ...

  9. WPF-如何添加用户控件(同一个程序集与非同一个程序集)

    在WPF中,假如十个按钮与十个文本框需要在窗体中多次使用,每次都都要重新添加这二十个按钮,显然是不可取的.这时,可以把这二十个按钮封装成一个UserControl,然后多次引用. 一.新建一个用户控件 ...

  10. ASP.NET Core: BackgroundService停止(StopAsync)后无法重新启动(StartAsync)的问题

    这里的 BackgroundService 是指: Microsoft.Extensions.Hosting.BackgroundService 1. 问题复现 继承该BackgroundServic ...