第十五周学习总结

第一部分:理论知识

JAR文件; 应用程序首选项存储; Java Web Start

JAR文件:

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

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

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

1 jar命令格式: jar {ctxui} [vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...

2 Jar命令选项:

– -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

第二部分:实验

1、实验目的与要求

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

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

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

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

2、实验内容和步骤

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

测试程序1

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

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

掌握创建JAR文件的方法;

  1. package A;
  2.  
  3. import java.awt.*;
  4.  
  5. import java.io.*;
  6. import java.net.*;
  7. import java.util.*;
  8. import javax.swing.*;
  9.  
  10. /**
  11. * @version 1.41 2015-06-12
  12. * @author Cay Horstmann
  13. */
  14. public class ResourceTest
  15. {
  16. public static void main(String[] args)
  17. {
  18. EventQueue.invokeLater(() -> {
  19. JFrame frame = new ResourceTestFrame();
  20. frame.setTitle("ResourceTest");
  21. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  22. frame.setVisible(true);
  23. });
  24. }
  25. }
  26.  
  27. /**
  28. * A frame that loads image and text resources.
  29. */
  30. class ResourceTestFrame extends JFrame
  31. {
  32. private static final int DEFAULT_WIDTH = 300;
  33. private static final int DEFAULT_HEIGHT = 300;
  34.  
  35. public ResourceTestFrame()
  36. {
  37. setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
  38. URL aboutURL = getClass().getResource("about.gif");
  39. Image img = new ImageIcon(aboutURL).getImage();
  40. setIconImage(img);
  41.  
  42. JTextArea textArea = new JTextArea();
  43. InputStream stream = getClass().getResourceAsStream("about.txt");
  44. try (Scanner in = new Scanner(stream, "UTF-8"))
  45. {
  46. while (in.hasNext())
  47. textArea.append(in.nextLine() + "\n");
  48. }
  49. add(textArea);
  50. }
  51. }
  1. Core Java: Fundamentals
  2. 10th Edition
  3. Cay Horstmann and Gary Cornell
  4. Copyright 2016
  5. Prentice-Hall
  1. Main-Class: resource.ResourceTest

测试程序2

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

了解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. * 一个测试属性的程序。 程序记住帧的位置、大小和标题
  12. * @version 1.01 2015-06-16
  13. * @author Cay Horstmann
  14. */
  15. public class PropertiesTest
  16. {
  17. public static void main(String[] args)
  18. {
  19. EventQueue.invokeLater(() -> {
  20. PropertiesFrame frame = new PropertiesFrame();
  21. frame.setVisible(true);
  22. });
  23. }
  24. }
  25.  
  26. /**
  27. * 从属性文件和更新恢复位置和大小的框架。退出时的属性。
  28. */
  29. class PropertiesFrame extends JFrame
  30. {
  31. private static final int DEFAULT_WIDTH = 300;
  32. private static final int DEFAULT_HEIGHT = 200;
  33.  
  34. private File propertiesFile;
  35. private Properties settings;
  36.  
  37. public PropertiesFrame()
  38. {
  39. // 从属性获取位置、大小、标题
  40.  
  41. String userDir = System.getProperty("user.home");
  42. File propertiesDir = new File(userDir, ".corejava");
  43. if (!propertiesDir.exists()) propertiesDir.mkdir();
  44. propertiesFile = new File(propertiesDir, "program.properties");
  45.  
  46. Properties defaultSettings = new Properties();
  47. defaultSettings.setProperty("left", "0");
  48. defaultSettings.setProperty("top", "0");
  49. defaultSettings.setProperty("width", "" + DEFAULT_WIDTH);
  50. defaultSettings.setProperty("height", "" + DEFAULT_HEIGHT);
  51. defaultSettings.setProperty("title", "");
  52.  
  53. settings = new Properties(defaultSettings);
  54.  
  55. if (propertiesFile.exists())
  56. try (InputStream in = new FileInputStream(propertiesFile))
  57. {
  58. settings.load(in);
  59. }
  60. catch (IOException ex)
  61. {
  62. ex.printStackTrace();
  63. }
  64.  
  65. int left = Integer.parseInt(settings.getProperty("left"));
  66. int top = Integer.parseInt(settings.getProperty("top"));
  67. int width = Integer.parseInt(settings.getProperty("width"));
  68. int height = Integer.parseInt(settings.getProperty("height"));
  69. setBounds(left, top, width, height);
  70.  
  71. // 如果没有标题,请询问用户
  72.  
  73. String title = settings.getProperty("title");
  74. if (title.equals(""))
  75. title = JOptionPane.showInputDialog("Please supply a frame title:");
  76. if (title == null) title = "";
  77. setTitle(title);
  78.  
  79. addWindowListener(new WindowAdapter()
  80. {
  81. public void windowClosing(WindowEvent event)
  82. {
  83. settings.setProperty("left", "" + getX());
  84. settings.setProperty("top", "" + getY());
  85. settings.setProperty("width", "" + getWidth());
  86. settings.setProperty("height", "" + getHeight());
  87. settings.setProperty("title", getTitle());
  88. try (OutputStream out = new FileOutputStream(propertiesFile))
  89. {
  90. settings.store(out, "Program Properties");
  91. }
  92. catch (IOException ex)
  93. {
  94. ex.printStackTrace();
  95. }
  96. System.exit(0);
  97. }
  98. });
  99. }
  100. }

测试程序3

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

了解Preferences类中常用的方法;

package preferences;

import java.awt.*;
import java.io.*;
import java.util.prefs.*;

import javax.swing.*;
import javax.swing.filechooser.*;

/**
* 一个测试偏好设置的程序。程序记住框架。位置、大小和标题。
* @version 1.03 2015-06-12
* @author Cay Horstmann
*/
public class PreferencesTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
PreferencesFrame frame = new PreferencesFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}

/**
* 从用户偏好恢复位置和大小并在退出时更新首选项的框架。
*/
class PreferencesFrame extends JFrame
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
private Preferences root = Preferences.userRoot();
private Preferences node = root.node("/com/horstmann/corejava");

public PreferencesFrame()
{
// 从偏好获得位置、大小、标题

int left = node.getInt("left", 0);
int top = node.getInt("top", 0);
int width = node.getInt("width", DEFAULT_WIDTH);
int height = node.getInt("height", DEFAULT_HEIGHT);
setBounds(left, top, width, height);

// 如果没有标题,请询问用户

String title = node.get("title", "");
if (title.equals(""))
title = JOptionPane.showInputDialog("Please supply a frame title:");
if (title == null) title = "";
setTitle(title);

// 设置显示XML文件的文件选择器

final JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileFilter(new FileNameExtensionFilter("XML files", "xml"));

// 设置菜单

JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);

JMenuItem exportItem = new JMenuItem("Export preferences");
menu.add(exportItem);
exportItem
.addActionListener(event -> {
if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)
{
try
{
savePreferences();
OutputStream out = new FileOutputStream(chooser
.getSelectedFile());
node.exportSubtree(out);
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});

JMenuItem importItem = new JMenuItem("Import preferences");
menu.add(importItem);
importItem
.addActionListener(event -> {
if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)
{
try
{
InputStream in = new FileInputStream(chooser
.getSelectedFile());
Preferences.importPreferences(in);
in.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});

JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(event -> {
savePreferences();
System.exit(0);
});
}

public void savePreferences()
{
node.putInt("left", getX());
node.putInt("top", getY());
node.putInt("width", getWidth());
node.putInt("height", getHeight());
node.put("title", getTitle());
}
}

      

测试程序4

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

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

  1. package webstart;
  2.  
  3. import java.awt.*;
  4. import javax.swing.*;
  5.  
  6. /**
  7. *
  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. public void setTitle()
  55. {
  56. try
  57. {
  58. String title = null;
  59.  
  60. BasicService basic = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
  61. URL codeBase = basic.getCodeBase();
  62.  
  63. PersistenceService service = (PersistenceService) ServiceManager
  64. .lookup("javax.jnlp.PersistenceService");
  65. URL key = new URL(codeBase, "title");
  66.  
  67. try
  68. {
  69. FileContents contents = service.get(key);
  70. InputStream in = contents.getInputStream();
  71. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  72. title = reader.readLine();
  73. }
  74. catch (FileNotFoundException e)
  75. {
  76. title = JOptionPane.showInputDialog("Please supply a frame title:");
  77. if (title == null) return;
  78.  
  79. service.create(key, 100);
  80. FileContents contents = service.get(key);
  81. OutputStream out = contents.getOutputStream(true);
  82. PrintStream printOut = new PrintStream(out);
  83. printOut.print(title);
  84. }
  85. setTitle(title);
  86. }
  87. catch (UnavailableServiceException | IOException e)
  88. {
  89. JOptionPane.showMessageDialog(this, e);
  90. }
  91. }
  92.  
  93. public void open()
  94. {
  95. try
  96. {
  97. FileOpenService service = (FileOpenService) ServiceManager
  98. .lookup("javax.jnlp.FileOpenService");
  99. FileContents contents = service.openFileDialog(".", new String[] { "txt" });
  100.  
  101. JOptionPane.showMessageDialog(this, contents.getName());
  102. if (contents != null)
  103. {
  104. InputStream in = contents.getInputStream();
  105. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  106. String line;
  107. while ((line = reader.readLine()) != null)
  108. {
  109. panel.append(line);
  110. panel.append("\n");
  111. }
  112. }
  113. }
  114. catch (UnavailableServiceException e)
  115. {
  116. JOptionPane.showMessageDialog(this, e);
  117. }
  118. catch (IOException e)
  119. {
  120. JOptionPane.showMessageDialog(this, e);
  121. }
  122. }
  123.  
  124. public void save()
  125. {
  126. try
  127. {
  128. ByteArrayOutputStream out = new ByteArrayOutputStream();
  129. PrintStream printOut = new PrintStream(out);
  130. printOut.print(panel.getText());
  131. InputStream data = new ByteArrayInputStream(out.toByteArray());
  132. FileSaveService service = (FileSaveService) ServiceManager
  133. .lookup("javax.jnlp.FileSaveService");
  134. service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt");
  135. }
  136. catch (UnavailableServiceException e)
  137. {
  138. JOptionPane.showMessageDialog(this, e);
  139. }
  140. catch (IOException e)
  141. {
  142. JOptionPane.showMessageDialog(this, e);
  143. }
  144. }
  145. }
  1. package webstart;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6. import javax.swing.text.*;
  7.  
  8. public class CalculatorPanel extends JPanel
  9. {
  10. private JTextArea display;
  11. private JPanel panel;
  12. private double result;
  13. private String lastCommand;
  14. private boolean start;
  15.  
  16. public CalculatorPanel()
  17. {
  18. setLayout(new BorderLayout());
  19.  
  20. result = 0;
  21. lastCommand = "=";
  22. start = true;
  23.  
  24. // 添加显示
  25. display = new JTextArea(10, 20);
  26.  
  27. add(new JScrollPane(display), BorderLayout.NORTH);
  28.  
  29. ActionListener insert = new InsertAction();
  30. ActionListener command = new CommandAction();
  31.  
  32. // 在4×4网格中添加按钮
  33.  
  34. panel = new JPanel();
  35. panel.setLayout(new GridLayout(4, 4));
  36.  
  37. addButton("7", insert);
  38. addButton("8", insert);
  39. addButton("9", insert);
  40. addButton("/", command);
  41.  
  42. addButton("4", insert);
  43. addButton("5", insert);
  44. addButton("6", insert);
  45. addButton("*", command);
  46.  
  47. addButton("1", insert);
  48. addButton("2", insert);
  49. addButton("3", insert);
  50. addButton("-", command);
  51.  
  52. addButton("0", insert);
  53. addButton(".", insert);
  54. addButton("=", command);
  55. addButton("+", command);
  56.  
  57. add(panel, BorderLayout.CENTER);
  58. }
  59.  
  60. public String getText()
  61. {
  62. return display.getText();
  63. }
  64.  
  65. public void append(String s)
  66. {
  67. display.append(s);
  68. }
  69.  
  70. private void addButton(String label, ActionListener listener)
  71. {
  72. JButton button = new JButton(label);
  73. button.addActionListener(listener);
  74. panel.add(button);
  75. }
  76.  
  77. private class InsertAction implements ActionListener
  78. {
  79. public void actionPerformed(ActionEvent event)
  80. {
  81. String input = event.getActionCommand();
  82. start = false;
  83. display.append(input);
  84. }
  85. }
  86.  
  87. private class CommandAction implements ActionListener
  88. {
  89. public void actionPerformed(ActionEvent event)
  90. {
  91. String command = event.getActionCommand();
  92.  
  93. if (start)
  94. {
  95. if (command.equals("-"))
  96. {
  97. display.append(command);
  98. start = false;
  99. }
  100. else
  101. lastCommand = command;
  102. }
  103. else
  104. {
  105. try
  106. {
  107. int lines = display.getLineCount();
  108. int lineStart = display.getLineStartOffset(lines - 1);
  109. int lineEnd = display.getLineEndOffset(lines - 1);
  110. String value = display.getText(lineStart, lineEnd - lineStart);
  111. display.append(" ");
  112. display.append(command);
  113. calculate(Double.parseDouble(value));
  114. if (command.equals("="))
  115. display.append("\n" + result);
  116. lastCommand = command;
  117. display.append("\n");
  118. start = true;
  119. }
  120. catch (BadLocationException e)
  121. {
  122. e.printStackTrace();
  123. }
  124. }
  125. }
  126. }
  127.  
  128. public void calculate(double x)
  129. {
  130. if (lastCommand.equals("+")) result += x;
  131. else if (lastCommand.equals("-")) result -= x;
  132. else if (lastCommand.equals("*")) result *= x;
  133. else if (lastCommand.equals("/")) result /= x;
  134. else if (lastCommand.equals("=")) result = x;
  135. }
  136. }

没有调试成功

实验2:GUI综合编程练习

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

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

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

按姓名字典序

输出人员信息;

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

查询最小年龄人员信息;

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

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

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

  1. package AA;
  2.  
  3. import java.awt.*;
  4. import javax.swing.*;
  5.  
  6. public class IdTest {
  7. public static void main(String[] args) {
  8. EventQueue.invokeLater(() -> {
  9. JFrame frame = new Main();
  10. frame.setTitle("身份证信息查询");
  11. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  12. frame.setVisible(true);
  13. });
  14. }
  15. }
  1. package AA;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.FileNotFoundException;
  8. import java.io.IOException;
  9. import java.util.ArrayList;
  10. import java.util.Arrays;
  11. import java.util.Collections;
  12. import java.util.Scanner;
  13. import java.awt.*;
  14. import javax.swing.*;
  15. import java.awt.event.*;
  16.  
  17. public class Main extends JFrame {
  18. private static ArrayList<Student> studentlist;
  19. private static ArrayList<Student> list;
  20. private JPanel panel;
  21. private JPanel buttonPanel;
  22. private static final int DEFAULT_WITH = 900;
  23. private static final int DEFAULT_HEIGHT = 600;
  24.  
  25. public Main() {
  26. studentlist = new ArrayList<>();
  27. Scanner scanner = new Scanner(System.in);
  28. File file = new File("G:\\身份证号.txt");
  29. try {
  30. FileInputStream fis = new FileInputStream(file);
  31. BufferedReader in = new BufferedReader(new InputStreamReader(fis));
  32. String temp = null;
  33. while ((temp = in.readLine()) != null) {
  34.  
  35. Scanner linescanner = new Scanner(temp);
  36.  
  37. linescanner.useDelimiter(" ");
  38. String name = linescanner.next();
  39. String number = linescanner.next();
  40. String sex = linescanner.next();
  41. String age = linescanner.next();
  42. String province = linescanner.nextLine();
  43. Student student = new Student();
  44. student.setName(name);
  45. student.setnumber(number);
  46. student.setsex(sex);
  47. int a = Integer.parseInt(age);
  48. student.setage(a);
  49. student.setprovince(province);
  50. studentlist.add(student);
  51.  
  52. }
  53. } catch (FileNotFoundException e) {
  54. System.out.println("文件找不到");
  55. e.printStackTrace();
  56. } catch (IOException e) {
  57. System.out.println("文件读取错误");
  58. e.printStackTrace();
  59. }
  60. panel = new JPanel();
  61. panel.setLayout(new BorderLayout());
  62. JTextArea A = new JTextArea();
  63. panel.add(A);
  64. add(panel, BorderLayout.NORTH);
  65. buttonPanel = new JPanel();
  66.  
  67. buttonPanel.setLayout(new GridLayout(6, 2));
  68. JButton jButton = new JButton("字典排序");
  69. JButton jButton1 = new JButton("年龄最大和年龄最小");
  70. JLabel lab1 = new JLabel("寻找你的老乡");
  71. JTextField a1 = new JTextField();
  72. JLabel lab2 = new JLabel("寻找找同龄人:");
  73. JTextField a2 = new JTextField();
  74. JLabel lab3 = new JLabel("输入身份证号码查询信息:");
  75. JTextField a3 = new JTextField();
  76. JButton jButton2 = new JButton("退出");
  77.  
  78. jButton.addActionListener(new ActionListener() {
  79. public void actionPerformed(ActionEvent e) {
  80. Collections.sort(studentlist);
  81. A.setText(studentlist.toString());
  82. }
  83. });
  84. jButton1.addActionListener(new ActionListener() {
  85. public void actionPerformed(ActionEvent e) {
  86. int max = 0, min = 100;
  87. int j, k1 = 0, k2 = 0;
  88. for (int i = 1; i < studentlist.size(); i++) {
  89. j = studentlist.get(i).getage();
  90. if (j > max) {
  91. max = j;
  92. k1 = i;
  93. }
  94. if (j < min) {
  95. min = j;
  96. k2 = i;
  97. }
  98.  
  99. }
  100. A.setText("年龄最大:" + studentlist.get(k1) + "年龄最小:" + studentlist.get(k2));
  101. }
  102. });
  103. jButton2.addActionListener(new ActionListener() {
  104. public void actionPerformed(ActionEvent e) {
  105. dispose();
  106. System.exit(0);
  107. }
  108. });
  109. a1.addActionListener(new ActionListener() {
  110. public void actionPerformed(ActionEvent e) {
  111. String find = a1.getText();
  112. String text="";
  113. String place = find.substring(0, 3);
  114. for (int i = 0; i < studentlist.size(); i++) {
  115. if (studentlist.get(i).getprovince().substring(1, 4).equals(place)) {
  116. text+="\n"+studentlist.get(i);
  117. A.setText("老乡:" + text);
  118. }
  119. }
  120. }
  121. });
  122. a2.addActionListener(new ActionListener() {
  123. public void actionPerformed(ActionEvent e) {
  124. String yourage = a2.getText();
  125. int a = Integer.parseInt(yourage);
  126. int near = agenear(a);
  127. int value = a - studentlist.get(near).getage();
  128. A.setText("年龄相近:" + studentlist.get(near));
  129. }
  130. });
  131. a3.addActionListener(new ActionListener() {
  132. public void actionPerformed(ActionEvent e) {
  133. list = new ArrayList<>();
  134. Collections.sort(studentlist);
  135. String key = a3.getText();
  136. for (int i = 1; i < studentlist.size(); i++) {
  137. if (studentlist.get(i).getnumber().contains(key)) {
  138. list.add(studentlist.get(i));
  139. A.setText("结果:\n" + list);
  140.  
  141. }
  142. }
  143. }
  144. });
  145. buttonPanel.add(jButton);
  146. buttonPanel.add(jButton1);
  147. buttonPanel.add(lab1);
  148. buttonPanel.add(a1);
  149. buttonPanel.add(lab2);
  150. buttonPanel.add(a2);
  151. buttonPanel.add(lab3);
  152. buttonPanel.add(a3);
  153. buttonPanel.add(jButton2);
  154. add(buttonPanel, BorderLayout.SOUTH);
  155. setSize(DEFAULT_WITH, DEFAULT_HEIGHT);
  156. }
  157.  
  158. public static int agenear(int age) {
  159. int min = 53, value = 0, k = 0;
  160. for (int i = 0; i < studentlist.size(); i++) {
  161. value = studentlist.get(i).getage() - age;
  162. if (value < 0)
  163. value = -value;
  164. if (value < min) {
  165. min = value;
  166. k = i;
  167. }
  168. }
  169. return k;
  170. }
  171.  
  172. }
  1. package AA;
  2.  
  3. public class Student implements Comparable<Student> {
  4.  
  5. private String name;
  6. private String number ;
  7. private String sex ;
  8. private int age;
  9. private String province;
  10.  
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public String getnumber() {
  18. return number;
  19. }
  20. public void setnumber(String number) {
  21. this.number = number;
  22. }
  23. public String getsex() {
  24. return sex ;
  25. }
  26. public void setsex(String sex ) {
  27. this.sex =sex ;
  28. }
  29. public int getage() {
  30.  
  31. return age;
  32. }
  33. public void setage(int age) {
  34.  
  35. this.age= age;
  36. }
  37.  
  38. public String getprovince() {
  39. return province;
  40. }
  41. public void setprovince(String province) {
  42. this.province=province ;
  43. }
  44.  
  45. public int compareTo(Student o) {
  46. return this.name.compareTo(o.getName());
  47. }
  48.  
  49. public String toString() {
  50. return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
  51. }
  52. }

            

      

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

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

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

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

  1. package BB;
  2.  
  3. import java.awt.Dimension;
  4. import java.awt.EventQueue;
  5. import java.awt.Toolkit;
  6.  
  7. import javax.swing.JFrame;
  8.  
  9. public class Main{
  10.  
  11. public static void main (String args[])
  12. {
  13. Toolkit t=Toolkit.getDefaultToolkit();
  14. Dimension s=t.getScreenSize();
  15. EventQueue.invokeLater(() -> {
  16. JFrame frame = new Calcultor();
  17. frame.setBounds(0, 0,(int)s.getWidth()/2,(int)s.getHeight()/2);
  18. frame.setTitle("练习界面");
  19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  20. frame.setVisible(true);
  21. });
  22. }
  23.  
  24. }
  1. package BB;
  2.  
  3. import java.awt.BorderLayout;
  4. import java.awt.Font;
  5. import java.awt.GridLayout;
  6. import java.awt.event.ActionEvent;
  7. import java.awt.event.ActionListener;
  8. import java.io.FileNotFoundException;
  9. import java.io.PrintWriter;
  10. import java.util.Collections;
  11. import java.util.Scanner;
  12.  
  13. import javax.swing.*;
  14.  
  15. import java.math.*;
  16.  
  17. public class Calcultor extends JFrame {
  18.  
  19. private static final int DEFAULT_WITH = 900;
  20. private static final int DEFAULT_HEIGHT = 600;
  21. private String[] c=new String[10];
  22. private String[] c1=new String[10];
  23. private int[] list=new int[10];
  24. int i=0,i1=0,sum = 0;
  25. private PrintWriter out = null;
  26. private JTextArea text,text1;
  27. private int counter;
  28. private JPanel buttonPanel;
  29.  
  30. public Calcultor() {
  31. JPanel Panel = new JPanel();
  32.  
  33. Panel.setLayout(null);
  34. JLabel JLabel1=new JLabel("题目");
  35.  
  36. buttonPanel = new JPanel();
  37. buttonPanel.setLayout(new GridLayout(1, 3));
  38.  
  39. JButton Button = new JButton("生成题目");
  40.  
  41. JButton Button2 = new JButton("确认答案");
  42.  
  43. JButton Button3 = new JButton("读出文本");
  44.  
  45. Button.addActionListener(new Action());
  46. Button2.addActionListener(new Action1());
  47. Button3.addActionListener(new Action2());
  48.  
  49. text=new JTextArea(30,80);
  50. text.setBounds(50, 50, 200, 50);
  51. //text.setFont(new Font("Courier",Font.PLAIN,35));
  52.  
  53. text1=new JTextArea(30,80);
  54. text1.setBounds(270, 50, 200, 50);
  55. //text1.setFont(new Font("Courier",Font.PLAIN,35));
  56.  
  57. Panel.add(text);
  58. Panel.add(text1);
  59.  
  60. buttonPanel.add(Button);
  61. buttonPanel.add(Button2);
  62. buttonPanel.add(Button3);
  63. Panel.add(JLabel1);
  64. add(Panel,BorderLayout.NORTH);
  65. add(buttonPanel, BorderLayout.SOUTH);
  66.  
  67. }
  68.  
  69. private class Action implements ActionListener
  70. {
  71. public void actionPerformed(ActionEvent event)
  72. {
  73. text1.setText("0");
  74. if(i<10) {
  75.  
  76. int a = 1+(int)(Math.random() * 99);
  77. int b = 1+(int)(Math.random() * 99);
  78. int m= (int) Math.round(Math.random() * 3);
  79. switch(m)
  80. {
  81. case 0:
  82. while(a<b){
  83. b = (int) Math.round(Math.random() * 100);
  84. a = (int) Math.round(Math.random() * 100);
  85. }
  86. c[i]=(i+":"+a+"/"+b+"=");
  87. list[i]=Math.floorDiv(a, b);
  88. text.setText(i+":"+a+"/"+b+"=");
  89. i++;
  90. break;
  91. case 1:
  92. c[i]=(i+":"+a+"*"+b+"=");
  93. list[i]=Math.multiplyExact(a, b);
  94. text.setText(i+":"+a+"*"+b+"=");
  95. i++;
  96. break;
  97. case 2:
  98. c[i]=(i+":"+a+"+"+b+"=");
  99. list[i]=Math.addExact(a, b);
  100. text.setText(i+":"+a+"+"+b+"=");
  101. i++;
  102. break ;
  103. case 3:
  104. while(a<=b){
  105. b = (int) Math.round(Math.random() * 100);
  106. a = (int) Math.round(Math.random() * 100);
  107. }
  108. c[i]=(i+":"+a+"-"+b+"=");
  109. text.setText(i+":"+a+"-"+b+"=");
  110. list[i]=Math.subtractExact(a, b);
  111. i++;
  112. break ;
  113. }
  114. }
  115. }
  116. }
  117. private class Action1 implements ActionListener
  118. {
  119. public void actionPerformed(ActionEvent event)
  120. {
  121. if(i<10) {
  122. text.setText(null);
  123. String daan=text1.getText().toString().trim();
  124. int a = Integer.parseInt(daan);
  125. if(text1.getText()!="") {
  126. if(list[i1]==a) sum+=10;
  127. }
  128. c1[i1]=daan;
  129. i1++;
  130. }
  131. }
  132. }
  133.  
  134. private class Action2 implements ActionListener
  135. {
  136. public void actionPerformed(ActionEvent event)
  137. {
  138.  
  139. try {
  140. out = new PrintWriter("text.txt");
  141. } catch (FileNotFoundException e) {
  142. // TODO Auto-generated catch block
  143. e.printStackTrace();
  144. }
  145. for(int counter=0;counter<10;counter++)
  146. {
  147. out.println(c[counter]+c1[counter]);
  148. }
  149. out.println("成绩"+sum);
  150. out.close();
  151.  
  152. }
  153.  
  154. }
  155.  

第三部分:

本周的作业没有完成。我意识到学习陷入了一种问题堆积的恶性循环,目前处于很危险的学习状态。

201771010134杨其菊《面向对象程序设计(java)》第十五周学习的更多相关文章

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

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

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

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

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

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

  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. 马凯军201771010116《面向对象程序设计Java》第八周学习总结

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

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

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

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

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

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

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

随机推荐

  1. Sublime Text 3 插件

    1.快捷键:ctrl+shift+P 2.输入install package,选择install package 3.输入需要安装的插件,选择安装 4.重启sublime 1. 格式化 html-cs ...

  2. jersey 用FastJson替换掉默认的Jackson

    @Bean public ResourceConfig resourceConfig() { ResourceConfig resourceConfig = new ResourceConfig(); ...

  3. xml模块学习

    import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml") root = tree.getroot() pr ...

  4. SQL注入--SQLMap过WAF

    单引号被过滤情况: 空格.等号未被过滤情况: select被过滤情况: 以此类推,当sqlmap注入出现问题时,比如不出数据,就要检查对应的关键词是否被过滤. 比如空格被过滤可以使用space2com ...

  5. Java小白不走弯路学习Java流程以及学习误区

    学习Java编程技术肯定是以就业拿到高薪工作为主要目的的,可是高薪不会那么轻易拿到,这是一个最简单的道理.没有付出就没有回报,在整个学习Java编程技术的过程中,你需要付出时间.精力.金钱.废话不多说 ...

  6. Django07-cookie和session

    一.Cookie 1.Cookie的由来 大家都知道HTTP协议是无状态的.无状态的意思是每次请求都是独立的,它的执行情况和结果与前面的请求和之后的请求都无直接关系,它不会受前面的请求响应情况直接影响 ...

  7. css样式基础详解

    一.字体属性:(font) 1.大小 {font-size: x-large;}(特大) xx-small;(极小) 一般中文用不到,只要用数值就可以,单位:PX.PD 2.样式 {font-styl ...

  8. spring @Bean注解的使用

    @Bean 的用法 @Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里.添加的bean的id为方法名 定义bean 下面是@Co ...

  9. thymeleaf标签必须由匹配的结束标记终止

    问题描述 springboot使用Thymeleaf标签时会报元素类型必须由匹配的结果标记终止. 如下所示 如果我们一个个的给这些元素后面加上终止标记也是件很麻烦的事~~~~ 解决办法 方法一: 在p ...

  10. 【读书笔记】segment routing mpls数据平面-1