201871010111-刘佳华《面向对象程序设计(java)》第十五周学习总结

实验十三  Swing图形界面组件(二)

实验时间 2019-12-6

第一部分:理论知识总结

5>.条(JSlider) 
滑动条在构造时默认是横向,如果需要纵向滑动条:

JSlider s = new JSlider(SwingConstants.VERTICAL,min,max,initialValue);
当滑动条滑动时,会触发ChangeEvent,需要调用addChangeListener()并且安装一个实现了ChangeListener接口的对象。这个接口只有一个StateChanged方法

//得到滑动条的当前值
ChangeListener listen = event ->{
JSlider s = (JSlider)event.getSource();
int val = s.getValue(); 
...
};
如果需要显示滑动条的刻度,则setPaintTicks(true); 
如果要将滑动条强制对准刻度,则setSnapToTicks(true); 
如果要为滑动条设置标签,则需要先构建一个Hashtable< Integer,Component>,将数字与标签对应起来,再调用setLabelTable(Dictionary label);

5.复杂的布局管理
1>GridBagLayout(网格组布局) 
即没有限制的网格布局,行和列的尺寸可以改变,且单元格可以合并 
过程: 
1)建议一个GridBagLayout对象,不需要指定行列数 
2)将容器setLayout为GBL对象 
3)为每个组件建立GridBagConstraints对象,即约束组件的大小以及排放方式 
4)通过add(component,constraints)增加组件 
使用帮助类来管理约束会方便很多。 
2>不使用布局管理器

frame.setLayout(null);
JButton btn = new JButton("Yes");
frame.add(btn);
btn.setBounds(10,10,100,30);
//void setBounds(int x,int y,int width,int height)//x,y表示左上角的坐标,width/height表示组件宽和高,Component类的方法
3>组件的遍历顺序(焦点的顺序):从左至右从上到下

component.setFocusable(false);//组件不设置焦点
6.菜单
分为JMenuBar/JMenu/JMenuItem,当选择菜单项时会触发一个动作事件,需要注册监听器监听

7.对话框
对话框分为模式对话框和无模对话框,模式对话框就是未处理此对话框之前不允许与其他窗口交互。 
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类) 
4>颜色对话框(JColorChooser类)

第二部分:实验部分

1、实验目的与要求

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

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

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

2、实验内容和步骤

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

测试程序1

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

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

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

代码如下:

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

MenuTest

 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;
//private TestAction saveAction; /**
* A sample action that prints the action name to System.out.
*/
class TestAction extends AbstractAction
{
public TestAction(String name)
{
super(name);
} public void actionPerformed(ActionEvent event)
{
System.out.println(getValue(Action.NAME) + " selected.");
}
} public MenuFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); JMenu fileMenu = new JMenu("File");
fileMenu.add(new TestAction("New"));//添加匿名类对象 // 演示加速器 JMenuItem openItem = fileMenu.add(new TestAction("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")); saveAsAction = new TestAction("Save As");
fileMenu.add(saveAsAction);
fileMenu.addSeparator(); fileMenu.add(new AbstractAction("Exit")
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
}); // 演示复选框和单选按钮菜单 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("C:\\Users\\83583\\Desktop\\java\\corejava\\v1ch11\\cut.gif"));
var copyAction = new TestAction("Copy");
copyAction.putValue(Action.SMALL_ICON, new ImageIcon("C:\\Users\\83583\\Desktop\\java\\corejava\\v1ch11\\copy.gif"));
var pasteAction = new TestAction("Paste");
pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("C:\\Users\\83583\\Desktop\\java\\corejava\\v1ch11\\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); // demonstrate mnemonics var helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H'); var 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 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);//在panel上设置弹出菜单
add(panel);
}
}

MenuFrame

   

1.点击Exit会关闭窗口

2.使用快捷键Ctrl+O和Ctrl+S,操作结果与鼠标点击相同:

通过控制台上显示单击菜单+selected,仿真模拟者个程序的实现过程:

3.Options子菜单(复选框和单选按钮菜单项)

测试程序2

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

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

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

代码如下:

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

ToolBarTest

 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); // 添加用于改变颜色的面板 panel = new JPanel();
add(panel, BorderLayout.CENTER); // 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(0);
}
};
exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");//The key used for storing a short Stringdescription for the action, used for tooltip text. // 填充工具栏 var bar = new JToolBar();
bar.add(blueAction);
bar.add(yellowAction);
bar.add(redAction);
bar.addSeparator();
bar.add(exitAction);
add(bar, BorderLayout.NORTH); // 填充菜单 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);
this.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)//javax.swing.AbstractAction.putValue(String key, Object newValue)
{ //构造coloraction的构造器
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);//设置背景颜色
}
}
}

ToolBarFrame

初始状态:

分别点击小图标之后,面板颜色会变化与小图标一致:(以蓝色为例)

将鼠标放置在四个按钮上都会有对应的提示(如图):

此外,除了小图标控制之后,菜单栏color也能实现同样的操作:

  •  问题与疑惑:

1.在于ColorAction类中的ColorAction构造器中的putValue方法

public ColorAction(String name, Icon icon, Color c)//javax.swing.AbstractAction.putValue(String key, Object newValue)
{ //构造coloraction的构造器
putValue(Action.NAME, name);
putValue(Action.SMALL_ICON, icon);
putValue(Action.SHORT_DESCRIPTION, name + " background");
putValue("Color", c);
}

.在程序中通过add(bar, BorderLayout.NORTH);设置工具栏在面板中的布局为边框布局北位置,但是在拖动工具栏时,

它的位置会发生变化,还可以将整个工具栏拖拽出面板(已解决):

      

工具栏的特殊之处在于它可以被随处移动,可以将其拖拽至框架的四个边框上(如上图1)也可以完全脱离框架(如上图2),

注意:工具栏只有位于采用边框布局或者支持NORTH,SOURTH,WEST,EAST,约束的布局管理器的容器中才能够被拖拽。

测试程序3

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

l 掌握选项对话框的用法。

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

 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(); // 为每个选项制作一个单选按钮
for (String option : options)
{
JRadioButton b = new JRadioButton(option);
b.setActionCommand(option);
add(b);
group.add(b);
b.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();
}
}

ButtonPanel

 package optionDialog;

 import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*; /**
* A frame that contains settings for selecting various option dialogs.
*/
public class OptionDialogFrame extends JFrame
{
private ButtonPanel typePanel;
private ButtonPanel messagePanel;
private ButtonPanel messageTypePanel;
private ButtonPanel optionTypePanel;
private ButtonPanel optionsPanel;
private ButtonPanel inputPanel;
private String messageString = "Message";
private Icon messageIcon = new ImageIcon("blue-ball.gif");
private Object messageObject = new Date();
private Component messageComponent = new SampleComponent(); public OptionDialogFrame()
{
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(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); // 添加带有“显示”按钮的面板 JPanel showPanel = new JPanel();
JButton showButton = new JButton("Show");
showButton.addActionListener(new ShowAction());
showPanel.add(showButton); add(gridPanel, BorderLayout.CENTER);
add(showPanel, BorderLayout.SOUTH);
pack();
} /**
* Gets the currently selected message.
* @return a string, icon, component, or object array, depending on the Message panel selection
*/
public Object getMessage()
{
String s = messagePanel.getSelection();
if (s.equals("String")) return messageString;
else if (s.equals("Icon")) return messageIcon;
else if (s.equals("Component")) return messageComponent;
else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
messageComponent, messageObject };
else if (s.equals("Other")) return messageObject;
else return null;
} /**
* Gets the currently selected options.
* @return an array of strings, icons, or objects, depending on the Option panel selection
*/
public Object[] getOptions()
{
String s = optionsPanel.getSelection();
if (s.equals("String[]")) return new String[] { "Yellow", "Blue", "Red" };
else if (s.equals("Icon[]")) return new Icon[] { new ImageIcon("yellow-ball.gif"),
new ImageIcon("blue-ball.gif"), new ImageIcon("red-ball.gif") };
else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
messageComponent, messageObject };
else return null;
} /**
* Gets the selected message or option type
* @param panel the Message Type or Confirm panel
* @return the selected XXX_MESSAGE or XXX_OPTION constant from the JOptionPane class
*/
public int getType(ButtonPanel panel)
{
String s = panel.getSelection();
try
{
return JOptionPane.class.getField(s).getInt(null);
}
catch (Exception e)
{
return -1;
}
} /**
* The action listener for the Show button shows a Confirm, Input, Message, or Option dialog
* depending on the Type panel selection.
*/
private class ShowAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (typePanel.getSelection().equals("Confirm")) JOptionPane.showConfirmDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel));
else if (typePanel.getSelection().equals("Input"))
{
if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
else JOptionPane.showInputDialog(OptionDialogFrame.this, getMessage(), "Title",
getType(messageTypePanel), null, new String[] { "Yellow", "Blue", "Red" },
"Blue");
}
else if (typePanel.getSelection().equals("Message")) JOptionPane.showMessageDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
else if (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog(
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel), null, getOptions(), getOptions()[0]);
}
}
} /**
* A component with a painted surface
*/ class SampleComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle2D 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);
}
}

OptionDialogFrame

 package optionDialog;

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

OptionDialogTest

运行截图:

 

测试程序4

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

l 掌握对话框的创建方法;

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

 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); // 将HTML标签添加到中心 add(
new JLabel(
"<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"),
BorderLayout.CENTER); // 确定按钮关闭对话框 JButton ok = new JButton("OK");
ok.addActionListener(event -> setVisible(false)); // 将“确定”按钮添加到南部边界 JPanel panel = new JPanel();
panel.add(ok);
add(panel, BorderLayout.SOUTH); pack();
}
}

AboutDialog

 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); // 构造一个文件菜单。 JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu); // 添加和退出菜单项。 // About项显示About对话框。 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); // 退出项退出程序。 JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(event -> System.exit(0));
fileMenu.add(exitItem);
}
}

DialogFrame

 package dialog;

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

DialogTest

运行截图:

测试程序5

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

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

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

 package dataExchange;

 import java.awt.*;
import java.awt.event.*;
import javax.swing.*; /**
* A frame with a menu whose File->Connect action shows a password dialog.
*/
public class DataExchangeFrame extends JFrame
{
public static final int TEXT_ROWS = 20;
public static final int TEXT_COLUMNS = 40;
private PasswordChooser dialog = null;
private JTextArea textArea; public DataExchangeFrame()
{
// 构造文件菜单 JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File");
mbar.add(fileMenu); // 添加连接和退出菜单项 JMenuItem connectItem = new JMenuItem("Connect");
connectItem.addActionListener(new ConnectAction());
fileMenu.add(connectItem); // 退出项退出程序 JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(event -> System.exit(0));
fileMenu.add(exitItem); textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
add(new JScrollPane(textArea), BorderLayout.CENTER);
pack();
} /**
* The Connect action pops up the password dialog.
*/
private class ConnectAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// 如果是第一次,则构造对话框 if (dialog == null) dialog = new PasswordChooser(); // 设置默认值
dialog.setUser(new User("yourname", null)); // pop up dialog
if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
{
// 如果接受,则检索用户输入
User u = dialog.getUser();
textArea.append("user name = " + u.getName() + ", password = "
+ (new String(u.getPassword())) + "\n");
}
}
}
}

DataExchangeFrame

 package dataExchange;

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

DataExchangeTest

 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()); // 使用用户名和密码字段构造面板 JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 2));
panel.add(new JLabel("User name:"));
panel.add(username = new JTextField(""));
panel.add(new JLabel("Password:"));
panel.add(password = new JPasswordField(""));
add(panel, BorderLayout.CENTER); // 创建终止对话框的“确定”和“取消”按钮 okButton = new JButton("Ok");
okButton.addActionListener(event -> {
ok = true;
dialog.setVisible(false);
}); JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(event -> dialog.setVisible(false)); // 将按钮添加到南边界 JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
add(buttonPanel, BorderLayout.SOUTH);
} /**
* Sets the dialog defaults.
* @param u the default user information
*/
public void setUser(User u)
{
username.setText(u.getName());
} /**
* Gets the dialog entries.
* @return a User object whose state represents the dialog entries
*/
public User getUser()
{
return new User(username.getText(), password.getPassword());
} /**
* Show the chooser panel in a dialog
* @param parent a component in the owner frame or null
* @param title the dialog window title
*/
public boolean showDialog(Component parent, String title)
{
ok = false; // locate the owner frame Frame owner = null;
if (parent instanceof Frame)
owner = (Frame) parent;
else
owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent); // if first time, or if owner has changed, make new dialog if (dialog == null || dialog.getOwner() != owner)
{
dialog = new JDialog(owner, true);
dialog.add(this);
dialog.getRootPane().setDefaultButton(okButton);
dialog.pack();
} // set title and show dialog dialog.setTitle(title);
dialog.setVisible(true);
return ok;
}
}

PasswordChooser

 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;
}
}

User

运行截图:

  

测试程序6

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

l 掌握文件对话框的用法;

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

 package fileChooser;

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

FileChooserTest

 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;
}
}

FileIconView

 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
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar); JMenu menu = new JMenu("File");
menuBar.add(menu); JMenuItem openItem = new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(event -> {
chooser.setCurrentDirectory(new File(".")); // 显示文件选择器对话框
int result = chooser.showOpenDialog(ImageViewerFrame.this); // 如果接受图像文件,请将其设置为标签的图标
if (result == JFileChooser.APPROVE_OPTION)
{
String name = chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(name));
pack();
}
}); JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(event -> System.exit(0)); // 使用标签显示图像
label = new JLabel();
add(label); // set up file chooser
chooser = new JFileChooser(); // 接受所有以.jpg、.jpeg、.gif结尾的图像文件
FileFilter 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")));
}
}

ImageViewerFrame

 package fileChooser;

 import java.awt.*;
import java.io.*; import javax.swing.*; /**
* A file chooser accessory that previews images.
*/
public class ImagePreviewer extends JLabel
{
/**
* Constructs an ImagePreviewer.
* @param chooser the file chooser whose property changes trigger an image
* change in this previewer
*/
public ImagePreviewer(JFileChooser chooser)
{
setPreferredSize(new Dimension(100, 100));
setBorder(BorderFactory.createEtchedBorder()); chooser.addPropertyChangeListener(event -> {
if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
{
// the user has selected a new file
File f = (File) event.getNewValue();
if (f == null)
{
setIcon(null);
return;
} // 将图像读入图标
ImageIcon icon = new ImageIcon(f.getPath()); // 如果图标太大而无法容纳,请缩放它
if (icon.getIconWidth() > getWidth())
icon = new ImageIcon(icon.getImage().getScaledInstance(
getWidth(), -1, Image.SCALE_DEFAULT)); setIcon(icon);
}
});
}
}

ImagePreviewer

运行截图:

  

 

测试程序7

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

l 了解颜色选择器的用法。

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

 package colorChooser;

 import javax.swing.*;

 /**
* A frame with a color chooser panel
*/
public class ColorChooserFrame extends JFrame
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200; public ColorChooserFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // 将颜色选择器面板添加到帧 ColorChooserPanel panel = new ColorChooserPanel();
add(panel);
}
}

ColorChooserFrame

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

ColorChooserPanel

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

ColorChooserTest

运行截图:

  

 

第三部分:实验心得

这一周继续学习了Swing用户界面组件以及GUI相关组件。在学习过程中,知识内容较多,也比较庞杂,自己对理论知识的学习也学的比较混乱,混淆了这几部分的学习内容,实验都有很多相同和类似的地方,在实验过程中任然没有理解的太清楚。在查了课本上的内容之后,稍微有了掌握。在运行程序过程中,对程序中有的代码还是不能理解,通过查书、上网查找才得以理解的同时也希望老师可以讲解一下。

 
 

201871010111-刘佳华《面向对象程序设计(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. Unity如何更改精灵中心点

      Unity虽然可以改中心点但是仅支持几个特定位置. 如果是一个你是切割的精灵,则可以进入精灵编辑器中调整 打开精灵编辑器后按调整如下图所示的pivot选项,我在这里把精灵调整成了右上. 在精灵编辑 ...

  2. go语言设计模式之builder

    builder.go package builder type BuildProcess interface { SetWheels() BuildProcess SetSeats() BuildPr ...

  3. Educational Codeforces Round 71 (Rated for Div. 2)

    传送门 A.There Are Two Types Of Burgers 签到. B.Square Filling 签到 C.Gas Pipeline 每个位置只有"高.低"两种状 ...

  4. linux 软件包的组成部分

    软件包的组成部分 1. 二进制文件 比如:/bin, /sbin & /usr/bin, /usr/sbin & /usr/local/bin, /usr/local/sbin 2.库 ...

  5. yum update 出错

    yum update 出错 : mirrors.163.com; Unknown error" Trying other mirror. yum-utils-1.1.31-52.el7.no ...

  6. Django restful framework中自动生成API文档

    自动生成api文档(不管是函数视图还是类视图都能显示) 1.安装rest_framework_swagger库 pip install django-rest-swagger 2.在项目下的 urls ...

  7. angular6 升级到 angular7+ 最新Ng-zorro

    angular7 出来有一段时间了,然后我们项目一直用的是angular6, 看到一直再用的Ng-Zorro 更新版本了,然后就觉得把目前的项目也升级一下把. 目前我本地cli版本是6.0.8我要把他 ...

  8. Golang 入门 : channel(通道)

    笔者在<Golang 入门 : 竞争条件>一文中介绍了 Golang 并发编程中需要面对的竞争条件.本文我们就介绍如何使用 Golang 提供的 channel(通道) 消除竞争条件. C ...

  9. Mybatis智能标签

    一.ProviderDao层 //智能标签案例 //智能标签多条件查询 public List<Provider> providerTest(@Param("proCode&qu ...

  10. IT兄弟连 Java语法教程 流程控制语句 分支结构语句5

    5  switch-case条件语句 Java中的第二种分支控制语句时switch语句,switch语句提供了多路支持,因此可以使程序在多个选项中进行选择.尽管一系列嵌套if语句可以执行多路测试,然而 ...