杨玲 201771010133《面向对象程序设计(java)》第十五周学习总结

java

面向对象程序设计(java)》第十五周学习总结

第一部分:理论知识学习部分

JAR文件:

1.Java程序的打包:程序编译完成后,程序员将.class文件压缩打包为.jar文件后,GUI界面程序就可以直接双击图标运行。

2.jar文件(Java归档)既可以包含类文件,也可包含诸如图像和声音这些其它类型的文件。

3.JAR文件是压缩的,它使用ZIP压缩格式。

jar命令 1 jar命令格式: jar {ctxui} [vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ... 2 Jar命令选项(教材581页表13-1): – -c 创建一个新的或者空的存档文件并加入文件。 – -C 暂时改变到指定的目录 – -e 在清单文件中创建一个条目 – -f 将JAR文件名指定为第二个命令行参数 – -i 为指定的JAR文件产生索引信息 – -m 将一个清单文件(manifest)添加到JAR文件中 – -M 不产生所有项的清单文件(manifest) – -t 列出存档内容的列表– -u 更新已存在的JAR文件 – -v 生成详细的输出结果 – -x 解压存档中的命名的(或所有的〕文件 – -0 只存储方式,不用ZIP压缩格式

(1) 创建JAR文件 jar cf jar-file input-file(s) c---want to Create a JAR file. eg: 1) jar cf MenuTest.jar *.class *.gif f---want the output to go to a file rather than to stdout. 2) jar cvf MenuTest.jar *.class *.gif v---Produces verbose output to stdout. 3) jar cvf MenuTest.jar * *---create all contents in current directory. 4) jar cv0f MenuTest.jar * 0---don't want the JAR file to be compressed.

(2) 查看JAR文件 jar tf jar-file t---want to view the Table of contents of the JAR file. eg: 1) jar tvf MenuTest.jar v---Produces verbose output to stdout.

(3) 提取JAR文件 jar xf jar-file [archived-file(s)] x---want to extract files from the JAR archive. eg: 1) jar xf MenuTest.jar copy.gif(仅提取文件copy.gif) 2) jar xf MenuTest.jar alex/copy.gif(仅提取目录alex下的 文件copy.gif) 3) jar xf MenuTest.jar(提取该JAR中的所有文件或目录)

(4) 更新JAR文件 jar uf jar-file input-file(s) u---want to update an existing JAR file. eg: 1) jar uf MenuTest.jar copy.gif (5) 索引JAR文件 jar i jar-file i---index an existing JAR file. eg: 1) jar i MenuTest.jar

清单文件

 每个JAR文件中包含一个用于描述归档特征的清单文件(manifest)。清单文件被命名为MANIFEST.MF,它位于JAR文件的一个特殊的META-INF子目录中。

 最小的符合标准的清单文件是很简单的:Manifest-Version:1.0复杂的清单文件包含多个条目,这些条目被分成多个节。第一节被称为主节,作用于整个JAR文件。随后的条目用来指定已命名条目的属性,可以是文件、包或者URL。

 清单文件的节与节之间用空行分开,最后一行必须以换行符结束。否则,清单文件将无法被正确地读取。

– 创建一个包含清单的JAR文件,应该运行:

jar cfm MyArchive.jar manifest.mf com/*.class

– 要更新一个已有JAR文件的清单,则需要将增加的部分

放置到一个文本文件中,运行如下命令:

jar ufm MyArchive.jar manifest-additions.mf

运行JAR文件

  用户可以通过下面的命令来启动应用程序:

java –jar MyProgram.jar

  窗口操作系统,可通过双击JAR文件图标来启动应用程序。

资源

  Java中,应用程序使用的类通常需要一些相关的数据文件,这些文件称为资源(Resource)。

–图像和声音文件。

–带有消息字符串和按钮标签的文本文件。

–二进制数据文件,如:描述地图布局的文件。

  类加载器知道如何搜索类文件,直到在类路径、存档文件或Web服务器上找到为止。

  利用资源机制对于非类文件也可以进行同样操作,具体步骤如下:

– 获得资源的Class对象。

– 如果资源是一个图像或声音文件,那么就需要调用getresource(filename)获得资源的URL位置,然后利用getImage或getAudioClip方法进行读取。

– 如果资源是文本或二进制文件,那么就可以使用getResouceAsStream方法读取文件中的数据。

  资源文件可以与类文件放在同一个目录中,也可以将资源文件放在其它子目录中。具体有以下两种方式:

–相对资源名:如data/text/about.txt它会被解释为相对于加载这个资源的类所在的包。

–绝对资源名:如/corejava/title.txt 

  ResourceTest.java程序演示了资源加载的过程。

   编译、创建JAR文件和执行这个程序的命令如下: – javac ResourceTest.java – jar cvfm ResourceTest.jar ResourceTest.mf *.class *.gif *.txt – java –jar ResourceTest.jar

第二部分:实验部分

  实验名称:GUI编程练习与应用程序部署

1、实验目的与要求

(1) 掌握Java应用程序的打包操作;

(2) 了解应用程序存储配置信息的两种方法;

(3) 掌握基于JNLP协议的java Web Start应用程序的发布方法;

(5) 掌握Java GUI 编程技术。

2、实验内容和步骤

实验1: 导入第13章示例程序,测试程序并进行代码注释。

测试程序1

l 在elipse IDE中调试运行教材585页程序13-1,结合程序运行结果理解程序;

l 将所生成的JAR文件移到另外一个不同的目录中,再运行该归档文件,以便确认程序是从JAR文件中,而不是从当前目录中读取的资源。

l 掌握创建JAR文件的方法;

 1 import java.awt.*;

2 import java.io.*;

3 import java.net.*;

4 import java.util.*;

5 import javax.swing.*;

6

7 /**

8 * @version 1.41 2015-06-12

9 * @author Cay Horstmann

10 */

11 public class ResourceTest

12 {

13 public static void main(String[] args)

14 {

15 EventQueue.invokeLater(() -> {

16 JFrame frame = new ResourceTestFrame();

17 frame.setTitle("ResourceTest");

18 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

19 frame.setVisible(true);

20 });

21 }

22 }

23

24 /**

25 * A frame that loads image and text resources.

26 */

27 class ResourceTestFrame extends JFrame

28 {

29 private static final int DEFAULT_WIDTH = 300;

30 private static final int DEFAULT_HEIGHT = 300;

31

32 public ResourceTestFrame()

33 {

34 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

35 URL aboutURL = getClass().getResource("about.gif");

36 Image img = new ImageIcon(aboutURL).getImage();

37 setIconImage(img);

38

39 JTextArea textArea = new JTextArea();

40 InputStream stream = getClass().getResourceAsStream("about.txt");

41 // 找到与类位于同一位置的资源,返回一个可以加载资源的URL或者输入流。

42 // 如果没有找到资源,则返回null,而且不会抛出异常或者发生I/O错误。

43 try (Scanner in = new Scanner(stream, "UTF-8"))

44 {

45 while (in.hasNext())

46 textArea.append(in.nextLine() + "\n");

47 }

48 add(textArea);

49 }

50 }

运行结果如下:

测试程序2

l 在elipse IDE中调试运行教材583页-584程序13-2,结合程序运行结果理解程序;

l 了解Properties类中常用的方法;

  1 package properties;

2

3 import java.awt.EventQueue;

4 import java.awt.event.*;

5 import java.io.*;

6 import java.util.Properties;

7

8 import javax.swing.*;

9

10 /**

11 * A program to test properties. The program remembers the frame position, size,

12 * and title.

13 * @version 1.01 2015-06-16

14 * @author Cay Horstmann

15 */

16 public class PropertiesTest

17 {

18 public static void main(String[] args)

19 {

20 EventQueue.invokeLater(() -> {

21 PropertiesFrame frame = new PropertiesFrame();

22 frame.setVisible(true);

23 });

24 }

25 }

26

27 /**

28 * A frame that restores position and size from a properties file and updates

29 * the properties upon exit.

30 */

31 class PropertiesFrame extends JFrame

32 {

33 private static final int DEFAULT_WIDTH = 300;

34 private static final int DEFAULT_HEIGHT = 200;

35

36 private File propertiesFile;

37 private Properties settings;

38

39 public PropertiesFrame()

40 {

41 // get position, size, title from properties

42

43 String userDir = System.getProperty("user.home");

44 //获取给定键名对应的系统属性。

45 //应用必须有权限获取这个属性,否则会抛出一个安全异常。

46 File propertiesDir = new File(userDir, ".corejava");

47 if (!propertiesDir.exists()) propertiesDir.mkdir();

48 propertiesFile = new File(propertiesDir, "program.properties");

49

50 Properties defaultSettings = new Properties();

51 defaultSettings.setProperty("left", "0");

52 defaultSettings.setProperty("top", "0");

53 defaultSettings.setProperty("width", "" + DEFAULT_WIDTH);

54 defaultSettings.setProperty("height", "" + DEFAULT_HEIGHT);

55 defaultSettings.setProperty("title", "");

56

57 settings = new Properties(defaultSettings);

58

59 if (propertiesFile.exists())

60 try (InputStream in = new FileInputStream(propertiesFile))

61 {

62 settings.load(in);

63 }

64 catch (IOException ex)

65 {

66 ex.printStackTrace();

67 }

68

69 int left = Integer.parseInt(settings.getProperty("left"));

70 int top = Integer.parseInt(settings.getProperty("top"));

71 int width = Integer.parseInt(settings.getProperty("width"));

72 int height = Integer.parseInt(settings.getProperty("height"));

73 setBounds(left, top, width, height);

74

75 // if no title given, ask user

76

77 String title = settings.getProperty("title");

78 if (title.equals(""))

79 title = JOptionPane.showInputDialog("Please supply a frame title:");

80 if (title == null) title = "";

81 setTitle(title);

82

83 addWindowListener(new WindowAdapter()

84 {

85 public void windowClosing(WindowEvent event)

86 {

87 settings.setProperty("left", "" + getX());

88 settings.setProperty("top", "" + getY());

89 settings.setProperty("width", "" + getWidth());

90 settings.setProperty("height", "" + getHeight());

91 settings.setProperty("title", getTitle());

92 try (OutputStream out = new FileOutputStream(propertiesFile))

93 {

94 settings.store(out, "Program Properties");

95 }

96 catch (IOException ex)

97 {

98 ex.printStackTrace();

99 }

100 System.exit(0);

101 }

102 });

103 }

104 }

运行结果如下:

测试程序3

l 在elipse IDE中调试运行教材593页-594程序13-3,结合程序运行结果理解程序;

l 了解Preferences类中常用的方法;

  1 import java.awt.*;

2 import java.io.*;

3 import java.util.prefs.*;

4

5 import javax.swing.*;

6 import javax.swing.filechooser.*;

7

8 /**

9 * A program to test preference settings. The program remembers the frame

10 * position, size, and title.

11 * @version 1.03 2015-06-12

12 * @author Cay Horstmann

13 */

14 public class PreferencesTest

15 {

16 public static void main(String[] args)

17 {

18 EventQueue.invokeLater(() -> {

19 PreferencesFrame frame = new PreferencesFrame();

20 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

21 frame.setVisible(true);

22 });

23 }

24 }

25

26 /**

27 * A frame that restores position and size from user preferences and updates the

28 * preferences upon exit.

29 */

30 class PreferencesFrame extends JFrame

31 {

32 private static final int DEFAULT_WIDTH = 300;

33 private static final int DEFAULT_HEIGHT = 200;

34 private Preferences root = Preferences.userRoot();

35 //返回调用程序的用户的首选项根节点。

36 private Preferences node = root.node("/com/horstmann/corejava");

37

38 public PreferencesFrame()

39 {

40 // get position, size, title from preferences

41

42 int left = node.getInt("left", 0);

43 //返回从当前节点由给定路径可以到达的节点。

44 //如果path是绝对路径(也就是说,以一个/开头),则从包含这个首选项节点的树的根节点开始查找。

45 //如果给定路径不存在相应的节点,则创建这样一个节点。

46 int top = node.getInt("top", 0);

47 int width = node.getInt("width", DEFAULT_WIDTH);

48 int height = node.getInt("height", DEFAULT_HEIGHT);

49 setBounds(left, top, width, height);

50

51 // if no title given, ask user

52

53 String title = node.get("title", "");

54 if (title.equals(""))

55 title = JOptionPane.showInputDialog("Please supply a frame title:");

56 if (title == null) title = "";

57 setTitle(title);

58

59 // set up file chooser that shows XML files

60

61 final JFileChooser chooser = new JFileChooser();

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

63 chooser.setFileFilter(new FileNameExtensionFilter("XML files", "xml"));

64

65 // set up menus 建立一个菜单

66

67 JMenuBar menuBar = new JMenuBar();

68 setJMenuBar(menuBar);

69 JMenu menu = new JMenu("File");

70 menuBar.add(menu);

71

72 JMenuItem exportItem = new JMenuItem("Export preferences");

73 menu.add(exportItem);

74 exportItem

75 .addActionListener(event -> {

76 if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)

77 {

78 try

79 {

80 savePreferences();

81 OutputStream out = new FileOutputStream(chooser

82 .getSelectedFile());

83 node.exportSubtree(out);

84 //将这个节点及其子节点的首选项写至指定的流

85 out.close();

86 }

87 catch (Exception e)

88 {

89 e.printStackTrace();

90 }

91 }

92 });

93

94 JMenuItem importItem = new JMenuItem("Import preferences");

95 menu.add(importItem);

96 importItem

97 .addActionListener(event -> {

98 if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)

99 {

100 try

101 {

102 InputStream in = new FileInputStream(chooser

103 .getSelectedFile());

104 Preferences.importPreferences(in);

105 in.close();

106 }

107 catch (Exception e)

108 {

109 e.printStackTrace();

110 }

111 }

112 });

113

114 JMenuItem exitItem = new JMenuItem("Exit");

115 menu.add(exitItem);

116 exitItem.addActionListener(event -> {

117 savePreferences();

118 System.exit(0);

119 });

120 }

121

122 public void savePreferences()

123 {

124 node.putInt("left", getX());

125 node.putInt("top", getY());

126 node.putInt("width", getWidth());

127 node.putInt("height", getHeight());

128 node.put("title", getTitle());

129 }

130 }

运行结果如下:

测试程序4

l 在elipse IDE中调试运行教材619页-622程序13-6,结合程序运行结果理解程序;

l 掌握基于JNLP协议的java Web Start应用程序的发布方法。

 1 package webstart;

2

3 import java.awt.*;

4 import javax.swing.*;

5

6 /**

7 * 具有可作为Java Web启动应用程序部署的计算历史的计算器。

8 * @version 1.04 2015-06-12

9 * @author Cay Horstmann

10 */

11 public class Calculator

12 {

13 public static void main(String[] args)

14 {

15 EventQueue.invokeLater(() -> {

16 CalculatorFrame frame = new CalculatorFrame();

17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

18 frame.setVisible(true);

19 });

20 }

21 }

  1 package webstart;

2

3 import java.io.BufferedReader;

4 import java.io.ByteArrayInputStream;

5 import java.io.ByteArrayOutputStream;

6 import java.io.FileNotFoundException;

7 import java.io.IOException;

8 import java.io.InputStream;

9 import java.io.InputStreamReader;

10 import java.io.OutputStream;

11 import java.io.PrintStream;

12 import java.net.MalformedURLException;

13 import java.net.URL;

14

15 import javax.jnlp.BasicService;

16 import javax.jnlp.FileContents;

17 import javax.jnlp.FileOpenService;

18 import javax.jnlp.FileSaveService;

19 import javax.jnlp.PersistenceService;

20 import javax.jnlp.ServiceManager;

21 import javax.jnlp.UnavailableServiceException;

22 import javax.swing.JFrame;

23 import javax.swing.JMenu;

24 import javax.swing.JMenuBar;

25 import javax.swing.JMenuItem;

26 import javax.swing.JOptionPane;

27

28 /**

29 * 一个带有计算器面板和菜单的框架,用来载入和保存计算器历史。

30 */

31 public class CalculatorFrame extends JFrame

32 {

33 private CalculatorPanel panel;

34

35 public CalculatorFrame()

36 {

37 setTitle();

38 panel = new CalculatorPanel();

39 add(panel);

40

41 JMenu fileMenu = new JMenu("File");

42 JMenuBar menuBar = new JMenuBar();

43 menuBar.add(fileMenu);

44 setJMenuBar(menuBar);

45

46 JMenuItem openItem = fileMenu.add("Open");

47 openItem.addActionListener(event -> open());

48 JMenuItem saveItem = fileMenu.add("Save");

49 saveItem.addActionListener(event -> save());

50

51 pack();

52 }

53

54 /**

55 * 从持久存储中获取标题,或者在没有以前的条目的情况下向用户请求标题。

56 */

57 public void setTitle()

58 {

59 try

60 {

61 String title = null;

62

63 BasicService basic = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");

64 URL codeBase = basic.getCodeBase();

65

66 PersistenceService service = (PersistenceService) ServiceManager

67 .lookup("javax.jnlp.PersistenceService");

68 URL key = new URL(codeBase, "title");

69

70 try

71 {

72 FileContents contents = service.get(key);

73 InputStream in = contents.getInputStream();

74 BufferedReader reader = new BufferedReader(new InputStreamReader(in));

75 title = reader.readLine();

76 }

77 catch (FileNotFoundException e)

78 {

79 title = JOptionPane.showInputDialog("Please supply a frame title:");

80 if (title == null) return;

81

82 service.create(key, 100);

83 FileContents contents = service.get(key);

84 OutputStream out = contents.getOutputStream(true);

85 PrintStream printOut = new PrintStream(out);

86 printOut.print(title);

87 }

88 setTitle(title);

89 }

90 catch (UnavailableServiceException | IOException e)

91 {

92 JOptionPane.showMessageDialog(this, e);

93 }

94 }

95

96 /**

97 * 打开历史文件并更新显示。

98 */

99 public void open()

100 {

101 try

102 {

103 FileOpenService service = (FileOpenService) ServiceManager

104 .lookup("javax.jnlp.FileOpenService");

105 FileContents contents = service.openFileDialog(".", new String[] { "txt" });

106

107 JOptionPane.showMessageDialog(this, contents.getName());

108 if (contents != null)

109 {

110 InputStream in = contents.getInputStream();

111 BufferedReader reader = new BufferedReader(new InputStreamReader(in));

112 String line;

113 while ((line = reader.readLine()) != null)

114 {

115 panel.append(line);

116 panel.append("\n");

117 }

118 }

119 }

120 catch (UnavailableServiceException e)

121 {

122 JOptionPane.showMessageDialog(this, e);

123 }

124 catch (IOException e)

125 {

126 JOptionPane.showMessageDialog(this, e);

127 }

128 }

129

130 /**

131 * 将计算器历史保存到文件中。

132 */

133 public void save()

134 {

135 try

136 {

137 ByteArrayOutputStream out = new ByteArrayOutputStream();

138 PrintStream printOut = new PrintStream(out);

139 printOut.print(panel.getText());

140 InputStream data = new ByteArrayInputStream(out.toByteArray());

141 FileSaveService service = (FileSaveService) ServiceManager

142 .lookup("javax.jnlp.FileSaveService");

143 service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt");

144 }

145 catch (UnavailableServiceException e)

146 {

147 JOptionPane.showMessageDialog(this, e);

148 }

149 catch (IOException e)

150 {

151 JOptionPane.showMessageDialog(this, e);

152 }

153 }

154 }

  1 package webstart;

2

3 import java.awt.*;

4 import java.awt.event.*;

5 import javax.swing.*;

6 import javax.swing.text.*;

7

8 /**

9 具有计算器按钮和结果显示的面板。

10 */

11 public class CalculatorPanel extends JPanel

12 {

13 private JTextArea display;

14 private JPanel panel;

15 private double result;

16 private String lastCommand;

17 private boolean start;

18

19 /**

20 列出面板。

21 */

22 public CalculatorPanel()

23 {

24 setLayout(new BorderLayout());

25

26 result = 0;

27 lastCommand = "=";

28 start = true;

29

30 // 添加显示

31 display = new JTextArea(10, 20);

32

33 add(new JScrollPane(display), BorderLayout.NORTH);

34

35 ActionListener insert = new InsertAction();

36 ActionListener command = new CommandAction();

37

38 // 在4×4网格中添加按钮

39

40 panel = new JPanel();

41 panel.setLayout(new GridLayout(4, 4));

42

43 addButton("7", insert);

44 addButton("8", insert);

45 addButton("9", insert);

46 addButton("/", command);

47

48 addButton("4", insert);

49 addButton("5", insert);

50 addButton("6", insert);

51 addButton("*", command);

52

53 addButton("1", insert);

54 addButton("2", insert);

55 addButton("3", insert);

56 addButton("-", command);

57

58 addButton("0", insert);

59 addButton(".", insert);

60 addButton("=", command);

61 addButton("+", command);

62

63 add(panel, BorderLayout.CENTER);

64 }

65

66 /**

67 获取历史文本。

68 @return the calculator history

69 */

70 public String getText()

71 {

72 return display.getText();

73 }

74

75 /**

76 将字符串追加到历史文本中。

77 @param s the string to append

78 */

79 public void append(String s)

80 {

81 display.append(s);

82 }

83

84 /**

85 向中心面板添加一个按钮。

86 @param label the button label

87 @param listener the button listener

88 */

89 private void addButton(String label, ActionListener listener)

90 {

91 JButton button = new JButton(label);

92 button.addActionListener(listener);

93 panel.add(button);

94 }

95

96 /**

97 此操作将按钮操作字符串插入到显示文本结束。

98 */

99 private class InsertAction implements ActionListener

100 {

101 public void actionPerformed(ActionEvent event)

102 {

103 String input = event.getActionCommand();

104 start = false;

105 display.append(input);

106 }

107 }

108

109 /**

110 此操作执行按钮的命令。动作字符串表示。

111 */

112 private class CommandAction implements ActionListener

113 {

114 public void actionPerformed(ActionEvent event)

115 {

116 String command = event.getActionCommand();

117

118 if (start)

119 {

120 if (command.equals("-"))

121 {

122 display.append(command);

123 start = false;

124 }

125 else

126 lastCommand = command;

127 }

128 else

129 {

130 try

131 {

132 int lines = display.getLineCount();

133 int lineStart = display.getLineStartOffset(lines - 1);

134 int lineEnd = display.getLineEndOffset(lines - 1);

135 String value = display.getText(lineStart, lineEnd - lineStart);

136 display.append(" ");

137 display.append(command);

138 calculate(Double.parseDouble(value));

139 if (command.equals("="))

140 display.append("\n" + result);

141 lastCommand = command;

142 display.append("\n");

143 start = true;

144 }

145 catch (BadLocationException e)

146 {

147 e.printStackTrace();

148 }

149 }

150 }

151 }

152

153 /**

154 执行悬而未决的计算。

155 @param x the value to be accumulated with the prior result.

156 */

157 public void calculate(double x)

158 {

159 if (lastCommand.equals("+")) result += x;

160 else if (lastCommand.equals("-")) result -= x;

161 else if (lastCommand.equals("*")) result *= x;

162 else if (lastCommand.equals("/")) result /= x;

163 else if (lastCommand.equals("=")) result = x;

164 }

165 }

运行结果如下:

实验2:GUI综合编程练习

按实验十四分组名单,组内讨论完成以下编程任务:

练习1:采用GUI界面设计以下程序,并进行部署与发布:

l 编制一个程序,将身份证号.txt 中的信息读入到内存中;

l 按姓名字典序输出人员信息;

l 查询最大年龄的人员信息;

l 查询最小年龄人员信息;

l 输入你的年龄,查询身份证号.txt中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;

l 查询人员中是否有你的同乡。

l 输入身份证信息,查询所提供身份证号的人员信息,要求输入一个身份证数字时,查询界面就显示满足查询条件的查询结果,且随着输入的数字的增多,查询匹配的范围逐渐缩小。

  1 import java.io.BufferedReader;

2 import java.io.File;

3 import java.io.FileInputStream;

4 import java.io.InputStreamReader;

5 import java.io.FileNotFoundException;

6 import java.io.IOException;

7 import java.util.ArrayList;

8 import java.util.Arrays;

9 import java.util.Collections;

10 import java.util.Scanner;

11 import java.awt.*;

12 import javax.swing.*;

13 import java.awt.event.*;

14

15 public class Main extends JFrame {

16 private static ArrayList<Student> studentlist;

17 private static ArrayList<Student> list;

18 private JPanel panel;

19 private JPanel buttonPanel;

20 private static final int DEFAULT_WITH = 800;

21 private static final int DEFAULT_HEIGHT = 600;

22

23 public Main() {

24 studentlist = new ArrayList<>();

25 Scanner scanner = new Scanner(System.in);

26 File file = new File("E:\\java\\身份证号.txt");

27 try {

28 FileInputStream fis = new FileInputStream(file);

29 BufferedReader in = new BufferedReader(new InputStreamReader(fis));

30 String temp = null;

31 while ((temp = in.readLine()) != null) {

32

33 Scanner linescanner = new Scanner(temp);

34

35 linescanner.useDelimiter(" ");

36 String name = linescanner.next();

37 String number = linescanner.next();

38 String sex = linescanner.next();

39 String age = linescanner.next();

40 String province = linescanner.nextLine();

41 Student student = new Student();

42 student.setName(name);

43 student.setnumber(number);

44 student.setsex(sex);

45 int a = Integer.parseInt(age);

46 student.setage(a);

47 student.setprovince(province);

48 studentlist.add(student);

49

50 }

51 } catch (FileNotFoundException e) {

52 System.out.println("学生信息文件找不到");

53 e.printStackTrace();

54 } catch (IOException e) {

55 System.out.println("学生信息文件读取错误");

56 e.printStackTrace();

57 }

58 panel = new JPanel();

59 panel.setLayout(new BorderLayout());

60 JTextArea jt = new JTextArea();

61 panel.add(jt);

62 add(panel, BorderLayout.NORTH);

63 buttonPanel = new JPanel();

64 buttonPanel.setLayout(new GridLayout(1, 7));

65 JButton jButton = new JButton("字典排序");

66 JButton jButton1 = new JButton("年龄最大和年龄最小");

67 JLabel lab = new JLabel("猜猜你的老乡");

68 JTextField jt1 = new JTextField();

69 JLabel lab1 = new JLabel("找找同龄人(年龄相近):");

70 JTextField jt2 = new JTextField();

71 JLabel lab2 = new JLabel("输入你的身份证号码:");

72 JTextField jt3 = new JTextField();

73 JButton jButton2 = new JButton("退出");

74 jButton.setBounds(110, 90, 60, 30);

75 jButton1.setBounds(110, 90, 60, 30);

76 jt1.setBounds(110, 90, 60, 30);

77 jt2.setBounds(110, 90, 60, 30);

78 jt3.setBounds(110, 90, 60, 30);

79 jButton2.setBounds(110, 90, 60, 30);

80 jButton.addActionListener(new ActionListener() {

81 public void actionPerformed(ActionEvent e) {

82 Collections.sort(studentlist);

83 jt.setText(studentlist.toString());

84 }

85 });

86 jButton1.addActionListener(new ActionListener() {

87 public void actionPerformed(ActionEvent e) {

88 int max = 0, min = 100;

89 int j, k1 = 0, k2 = 0;

90 for (int i = 1; i < studentlist.size(); i++) {

91 j = studentlist.get(i).getage();

92 if (j > max) {

93 max = j;

94 k1 = i;

95 }

96 if (j < min) {

97 min = j;

98 k2 = i;

99 }

100

101 }

102 jt.setText("年龄最大:" + studentlist.get(k1) + "年龄最小:" + studentlist.get(k2));

103 }

104 });

105 jButton2.addActionListener(new ActionListener() {

106 public void actionPerformed(ActionEvent e) {

107 dispose();

108 System.exit(0);

109 }

110 });

111 jt1.addActionListener(new ActionListener() {

112 public void actionPerformed(ActionEvent e) {

113 String find = jt1.getText();

114 String text="";

115 String place = find.substring(0, 3);

116 for (int i = 0; i < studentlist.size(); i++) {

117 if (studentlist.get(i).getprovince().substring(1, 4).equals(place)) {

118 text+="\n"+studentlist.get(i);

119 jt.setText("老乡:" + text);

120 }

121 }

122 }

123 });

124 jt2.addActionListener(new ActionListener() {

125 public void actionPerformed(ActionEvent e) {

126 String yourage = jt2.getText();

127 int a = Integer.parseInt(yourage);

128 int near = agenear(a);

129 int value = a - studentlist.get(near).getage();

130 jt.setText("年龄相近:" + studentlist.get(near));

131 }

132 });

133 jt3.addActionListener(new ActionListener() {

134 public void actionPerformed(ActionEvent e) {

135 list = new ArrayList<>();

136 Collections.sort(studentlist);

137 String key = jt3.getText();

138 for (int i = 1; i < studentlist.size(); i++) {

139 if (studentlist.get(i).getnumber().contains(key)) {

140 list.add(studentlist.get(i));

141 jt.setText("emmm!你可能是:\n" + list);

142

144 }

145 }

146 }

147 });

148 buttonPanel.add(jButton);

149 buttonPanel.add(jButton1);

150 buttonPanel.add(lab);

151 buttonPanel.add(jt1);

152 buttonPanel.add(lab1);

153 buttonPanel.add(jt2);

154 buttonPanel.add(lab2);

155 buttonPanel.add(jt3);

156 buttonPanel.add(jButton2);

157 add(buttonPanel, BorderLayout.SOUTH);

158 setSize(DEFAULT_WITH, DEFAULT_HEIGHT);

159 }

160

161 public static int agenear(int age) {

162 int min = 53, value = 0, k = 0;

163 for (int i = 0; i < studentlist.size(); i++) {

164 value = studentlist.get(i).getage() - age;

165 if (value < 0)

166 value = -value;

167 if (value < min) {

168 min = value;

169 k = i;

170 }

171 }

172 return k;

173 }

174

175 }

 1 public class Student implements Comparable<Student> {

2

3 private String name;

4 private String number ;

5 private String sex ;

6 private int age;

7 private String province;

8

9 public String getName() {

10 return name;

11 }

12 public void setName(String name) {

13 this.name = name;

14 }

15 public String getnumber() {

16 return number;

17 }

18 public void setnumber(String number) {

19 this.number = number;

20 }

21 public String getsex() {

22 return sex ;

23 }

24 public void setsex(String sex ) {

25 this.sex =sex ;

26 }

27 public int getage() {

28

29 return age;

30 }

31 public void setage(int age) {

32 // int a = Integer.parseInt(age);

33 this.age= age;

34 }

35

36 public String getprovince() {

37 return province;

38 }

39 public void setprovince(String province) {

40 this.province=province ;

41 }

42

43 public int compareTo(Student o) {

44 return this.name.compareTo(o.getName());

45 }

46

47 public String toString() {

48 return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";

49 }

50 }

 1 import java.awt.*;

2 import javax.swing.*;

3

4 public class ButtonTest {

5 public static void main(String[] args) {

6 EventQueue.invokeLater(() -> {

7 JFrame frame = new Main();

8 frame.setTitle("身份证信息");

9 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

10 frame.setVisible(true);

11 });

12 }

13 }

运行结果如下:

                                                           

练习2:采用GUI界面设计以下程序,并进行部署与发布

l 编写一个计算器类,可以完成加、减、乘、除的操作

l 利用计算机类,设计一个小学生100以内数的四则运算练习程序,由计算机随机产生10道加减乘除练习题,学生输入答案,由程序检查答案是否正确,每道题正确计10分,错误不计分,10道题测试结束后给出测试总分;

l 将程序中测试练习题及学生答题结果输出到文件,文件名为test.txt。

  1 import java.awt.BorderLayout;

2 import java.awt.GridLayout;

3 import java.awt.event.ActionEvent;

4 import java.awt.event.ActionListener;

5 import javax.swing.JButton;

6 import javax.swing.JFrame;

7 import javax.swing.JPanel;

8 import javax.swing.JTextField;

9 public class Calculator extends JFrame {

10 JButton b0 = new JButton("0");

11 JButton b1 = new JButton("1");

12 JButton b2 = new JButton("2");

13 JButton b3 = new JButton("3");

14 JButton b4 = new JButton("4");

15 JButton b5 = new JButton("5");

16 JButton b6 = new JButton("6");

17 JButton b7 = new JButton("7");

18 JButton b8 = new JButton("8");

19 JButton b9 = new JButton("9");

20 JButton jiaButton = new JButton("+");

21 JButton jianButton = new JButton("-");

22 JButton chengButton = new JButton("*");

23 JButton chuButton = new JButton("/");

24 JButton yuButton = new JButton("%");

25 JButton jjButton = new JButton("+/-");

26 JButton sqrtButton = new JButton("sqrt");

27 JButton dianButton = new JButton(".");

28 JButton dengButton = new JButton("=");

29 JButton daoButton = new JButton("1/x");

30 JButton backButton = new JButton("Backpace");

31 JButton cButton = new JButton("C");

32 public double op1;

33 public double op2;

34 public static final int JIA = 0;

35 public static final int JIAN = 1;

36 public static final int CHENG = 2;

37 public static final int CHU = 3;

38 public static final int JJ = 4;

39 public static final int DIAN = 5;

40 public int current0p = 0;

41 private boolean opEnd = false;

42 JPanel panel1 = new JPanel();

43 JPanel panel2 = new JPanel();

44 JPanel panel3 = new JPanel();

45 JPanel panel4 = new JPanel();

46 JTextField result = new JTextField(20);

47 public Calculator() {

48 initPanel2();

49 initPanel3();

50 panel2.setLayout(new GridLayout(5, 4));

51 panel1.setLayout(new BorderLayout());

52 panel1.add(panel3, BorderLayout.NORTH);// 设置位置

53 panel1.add(panel2, BorderLayout.CENTER);// 设置位置

54 getContentPane().add(panel1);

55 addActionListeners();

56 setSize(260, 260);

57 setLocation(500, 300);

58 setVisible(true);

59 setDefaultCloseOperation(Calculator.EXIT_ON_CLOSE);

60 this.setResizable(false);

61 this.setTitle("计算器");

62 }

63 private void initPanel2() {

64 // 把组件添加相应panel上

65 panel2.add(b7);

66 panel2.add(b8);

67 panel2.add(b9);

68 panel2.add(chuButton);

69 panel2.add(b4);

70 panel2.add(b5);

71 panel2.add(b6);

72 panel2.add(chengButton);

73 panel2.add(b1);

74 panel2.add(b2);

75 panel2.add(b3);

76 panel2.add(jianButton);

77 panel2.add(b0);

78 panel2.add(jjButton);

79 panel2.add(dianButton);

80 panel2.add(jiaButton);

81 panel2.add(daoButton);

82 panel2.add(yuButton);

83 panel2.add(sqrtButton);

84 panel2.add(dengButton);

85 }

86 private void addActionListeners() {

87 ActionHandler c = new ActionHandler();

88 b0.addActionListener(c);

89 b1.addActionListener(c);

90 b2.addActionListener(c);

91 b3.addActionListener(c);

92 b4.addActionListener(c);

93 b5.addActionListener(c);

94 b6.addActionListener(c);

95 b7.addActionListener(c);

96 b8.addActionListener(c);

97 b9.addActionListener(c);

98 jiaButton.addActionListener(c);

99 dengButton.addActionListener(c);

100 chengButton.addActionListener(c);

101 chuButton.addActionListener(c);

102 jianButton.addActionListener(c);

103 jjButton.addActionListener(c);

104 dianButton.addActionListener(c);

105 sqrtButton.addActionListener(c);

106 yuButton.addActionListener(c);

107 daoButton.addActionListener(c);

108 backButton.addActionListener(c);

109 cButton.addActionListener(c);

110 }

111 class ActionHandler implements ActionListener {

112 public void actionPerformed(ActionEvent e) {

113 if (e.getSource() == b0) {

114 if (opEnd == false) {

115 result.setText("");

116 }

117 result.setText(result.getText() + "0");

118 }

119 if (e.getSource() == b1) {

120 if (opEnd == false) {

121 result.setText("");

122 }

123 result.setText(result.getText() + "1");

124 opEnd = true;

125 }

126 if (e.getSource() == b2) {

127 if (opEnd == false) {

128 result.setText("");

129 }

130 result.setText(result.getText() + "2");

131 opEnd = true;

132 }

133 if (e.getSource() == b3) {

134 if (opEnd == false) {

135 result.setText("");

136 }

137 result.setText(result.getText() + "3");

138 opEnd = true;

139 }

140 if (e.getSource() == b4) {

141 if (opEnd == false) {

142 result.setText("");

143 }

144 result.setText(result.getText() + "4");

145 opEnd = true;

146 }

147 if (e.getSource() == b5) {

148 if (opEnd == false) {

149 result.setText("");

150 }

151 result.setText(result.getText() + "5");

152 opEnd = true;

153 }

154 if (e.getSource() == b6) {

155 if (opEnd == false) {

156 result.setText("");

157 }

158 result.setText(result.getText() + "6");

159 opEnd = true;

160 }

161 if (e.getSource() == b7) {

162 if (opEnd == false) {

163 result.setText("");

164 }

165 result.setText(result.getText() + "7");

166 opEnd = true;

167 }

168 if (e.getSource() == b8) {

169 if (opEnd == false) {

170 result.setText("");

171 }

172 result.setText(result.getText() + "8");

173 opEnd = true;

174 }

175 if (e.getSource() == b9) {

176 if (opEnd == false) {

177 result.setText("");

178 }

179 result.setText(result.getText() + "9");

180 opEnd = true;

181 }

182 try {

183 if (e.getSource() == jiaButton) {

184 op1 = Double.parseDouble(result.getText());

185 // 2、说明操作数已经输入完毕

186 opEnd = false;

187 current0p = JIA;

188 }

189 if (e.getSource() == chengButton) {

190 op1 = Double.parseDouble(result.getText());

191 // 2、说明操作数已经输入完毕

192 opEnd = false;

193 current0p = CHENG;

194 }

195 if (e.getSource() == chuButton) {

196 op1 = Double.parseDouble(result.getText());

197 // 2、说明操作数已经输入完毕

198 opEnd = false;

199 current0p = CHU;

200 }

201 if (e.getSource() == jianButton) {

202 op1 = Double.parseDouble(result.getText());

203 // 2、说明操作数已经输入完毕

204 opEnd = false;

205 current0p = JIAN;

206 }

207 if (e.getSource() == jjButton) {

208 String tmp = result.getText();

209 if (tmp.equals("") || tmp.equals("0")) {

210 return;

211 }

212 if (tmp.charAt(0) == '-') {

213 tmp = tmp.substring(1);

214 } else {

215 tmp = '-' + tmp;

216 }

217 result.setText(tmp);

218 }

219 if (e.getSource() == dianButton) {

220 String tmp = result.getText();

221 if (tmp.equals("")) {

222 return;

223 }

224 if (tmp.indexOf(".") != -1) {

225 return;

226 }

227 tmp = tmp + ".";

228 result.setText(tmp);

229 }

230 if (e.getSource() == sqrtButton) {

231 String tmp = result.getText();

232 if (tmp.equals(" ")) {

233 return;

234 }

235 double d;

236 d = Double.parseDouble(tmp);// 先定义double类型d

237 if (d < 0) {

238 result.setText("不能对负数求平方根");

239 return;

240 }

241 op2 = Math.sqrt(d);

242 result.setText(op2 + "");

243 }

244 if (e.getSource() == backButton) {

245 String s = result.getText();

246 result.setText("");

247 for (int i = 0; i < s.length() - 1; i++) {

248 char a = s.charAt(i);

249 result.setText(result.getText() + a);

250 }

251 }

252 if (e.getSource() == cButton) {

253 result.setText("0");

254 opEnd = false;

255 }

256 if (e.getSource() == dengButton) {

257 op2 = Double.parseDouble(result.getText());

258 switch (current0p) {

259 case JIA:

260 result.setText(op1 + op2 + "");

261 break;

262 case JIAN:

263 result.setText(op1 - op2 + "");

264 break;

265 case CHENG:

266 result.setText(op1 * op2 + "");

267 break;

268 case CHU:

269 if (op2 == 0) {

270 result.setText("被除数不能为零");

271 break;

272 }

273 result.setText(op1 / op2 + "");

274 break;

275 }

276 opEnd = false;

277 }

278 } catch (Exception e1) {

279 result.setText("Wrong");

280 opEnd = false;

281 }

282 }

283 }

284 private void initPanel3() {

285 panel3.setLayout(new GridLayout(2, 1));

286 panel3.add(result);

287 panel3.add(panel4);

288 panel4.setLayout(new GridLayout(1, 2));

289 panel4.add(backButton);

290 panel4.add(cButton);

291 }

292 public static void main(String[] args) {

293 Calculator c = new Calculator();// 生成类实例

294 }

295 }

 1 import java.io.FileNotFoundException;

2 import java.io.PrintWriter;

3 import java.util.Scanner;

4

5 /*

6 * 该程序用来随机生成0到100以内的加减乘除题

7 */

8 public class Demo {

9 public static void main(String[] args) {

10 // 用户的答案要从键盘输入,因此需要一个键盘输入流

11 Scanner in = new Scanner(System.in);

12 Counter counter=new Counter();

13 PrintWriter out = null;

14 try {

15 out = new PrintWriter("text.txt");

16 } catch (FileNotFoundException e) {

17 // TODO Auto-generated catch block

18 e.printStackTrace();

19 }

20 // 定义一个变量用来统计得分

21 int sum = 0;

22 int k=0;

23 // 通过循环生成10道题

24 for (int i = 0; i < 10; i++) {

25

26 // 随机生成两个100以内的随机数作加减乘除

27 int a = (int) Math.round(Math.random() * 100);

28 int b = (int) Math.round(Math.random() * 100);

29 int d = (int) Math.round(Math.random() * 3);

30

31 switch (d){

32

33 case 0:

34 if(a%b == 0) {

35 System.out.println(a + "/" + b + "=");

36 break;

37 }

38 //int c = in.nextInt();

39 //out.println(a + "/" + b + "="+c);

40 case 1:

41 System.out.println(a + "*" + b + "=");

42 //int c1 = in.nextInt();

43 //out.println(a + "*" + b + "="+c1);

44 break;

45 case 2:

46 System.out.println(a + "+" + b + "=");

47 //int c2 = in.nextInt();

48 //out.println(a + "+" + b + "="+c2);

49 break;

50 case 3:

51 if(a>b) {

52 System.out.println(a + "-" + b + "=");

53 break;

54 }

55 //int c3 = in.nextInt();

56 //out.println(a + "-" + b + "="+c3);

57

58 }

59

60 // 定义一个整数用来接收用户输入的答案

61 double c = in.nextDouble();

62

63 // 判断用户输入的答案是否正确,正确给10分,错误不给分

64 if (c == a / b | c == a * b | c == a + b | c == a - b) {

65 sum += 10;

66 System.out.println("恭喜答案正确");

67 }

68 else {

69 System.out.println("抱歉,答案错误");

70

71 }

72 out.println(a + "/" + b + "="+c );

73 out.println(a + "*" + b + "="+c);

74 out.println(a + "+" + b + "="+c);

75 out.println(a + "-" + b + "="+c);

76

77 }

78 //输出用户的成绩

79 System.out.println("你的得分为"+sum);

80

81 out.println("成绩:"+sum);

82 out.close();

83 }

84 }

4. 实验总结:

  通过本次实验,我发现了自己在学习中还存在很大的问题与不足,在学习Java编程这条路上还有很长的路要走。

以上是 杨玲 201771010133《面向对象程序设计(java)》第十五周学习总结 的全部内容, 来源链接: utcz.com/z/394551.html

回到顶部