马凯军201771010116《面向对象与程序设计Java》第十五周学习知识总结

                                                                                 实验十五  GUI编程练习与应用程序部署

一、知识学习部分

清单文件

每个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

扫描二维码关注公众号,回复: 4436470 查看本文章

运行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

实验时间 2018-12-6

1、实验目的与要求

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

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

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

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

2、实验内容和步骤

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

测试程序1

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

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

3.掌握创建JAR文件的方法;

复制代码
 1 package resource;
 2 
 3 import java.awt.*;  4 import java.io.*;  5 import java.net.*;  6 import java.util.*;  7 import javax.swing.*;  8  9 /** 10  * @version 1.41 2015-06-12 11  * @author Cay Horstmann 12 */ 13 public class ResourceTest 14 { 15 public static void main(String[] args) 16  { 17 EventQueue.invokeLater(() -> { 18 JFrame frame = new ResourceTestFrame(); 19 frame.setTitle("ResourceTest"); 20  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 21 frame.setVisible(true); 22  }); 23  } 24 } 25 26 /** 27  * 一个加载图像和文本资源的框架。 28 */ 29 class ResourceTestFrame extends JFrame 30 { 31 private static final int DEFAULT_WIDTH = 300; 32 private static final int DEFAULT_HEIGHT = 300; 33 34 public ResourceTestFrame() 35  { 36  setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 37 URL aboutURL = getClass().getResource("about.gif"); 38 Image img = new ImageIcon(aboutURL).getImage(); 39  setIconImage(img); 40 41 JTextArea textArea = new JTextArea(); 42 InputStream stream = getClass().getResourceAsStream("about.txt"); 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

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

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

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

2.了解Preferences类中常用的方法;

复制代码
  1 package preferences;
  2 
  3 import java.awt.*;  4 import java.io.*;  5 import java.util.prefs.*;  6  7 import javax.swing.*;  8 import javax.swing.filechooser.*;  9  10 /**  11  * 一个测试偏好设置的程序。程序记住框架。位置、大小和标题。  12  * @version 1.03 2015-06-12  13  * @author Cay Horstmann  14 */  15 public class PreferencesTest  16 {  17 public static void main(String[] args)  18  {  19 EventQueue.invokeLater(() -> {  20 PreferencesFrame frame = new PreferencesFrame();  21  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  22 frame.setVisible(true);  23  });  24  }  25 }  26  27 /**  28  * 从用户偏好恢复位置和大小并在退出时更新首选项的框架。  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 private Preferences node = root.node("/com/horstmann/corejava");  36  37 public PreferencesFrame()  38  {  39 // 从偏好获得位置、大小、标题  40  41 int left = node.getInt("left", 0);  42 int top = node.getInt("top", 0);  43 int width = node.getInt("width", DEFAULT_WIDTH);  44 int height = node.getInt("height", DEFAULT_HEIGHT);  45  setBounds(left, top, width, height);  46  47 // 如果没有标题,请询问用户  48  49 String title = node.get("title", "");  50 if (title.equals(""))  51 title = JOptionPane.showInputDialog("Please supply a frame title:");  52 if (title == null) title = "";  53  setTitle(title);  54  55 // 设置显示XML文件的文件选择器  56  57 final JFileChooser chooser = new JFileChooser();  58 chooser.setCurrentDirectory(new File("."));  59 chooser.setFileFilter(new FileNameExtensionFilter("XML files", "xml"));  60  61 // 设置菜单  62  63 JMenuBar menuBar = new JMenuBar();  64  setJMenuBar(menuBar);  65 JMenu menu = new JMenu("File");  66  menuBar.add(menu);  67  68 JMenuItem exportItem = new JMenuItem("Export preferences");  69  menu.add(exportItem);  70  exportItem  71 .addActionListener(event -> {  72 if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)  73  {  74 try  75  {  76  savePreferences();  77 OutputStream out = new FileOutputStream(chooser  78  .getSelectedFile());  79  node.exportSubtree(out);  80  out.close();  81  }  82 catch (Exception e)  83  {  84  e.printStackTrace();  85  }  86  }  87  });  88  89 JMenuItem importItem = new JMenuItem("Import preferences");  90  menu.add(importItem);  91  importItem  92 .addActionListener(event -> {  93 if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)  94  {  95 try  96  {  97 InputStream in = new FileInputStream(chooser  98  .getSelectedFile());  99  Preferences.importPreferences(in); 100  in.close(); 101  } 102 catch (Exception e) 103  { 104  e.printStackTrace(); 105  } 106  } 107  }); 108 109 JMenuItem exitItem = new JMenuItem("Exit"); 110  menu.add(exitItem); 111 exitItem.addActionListener(event -> { 112  savePreferences(); 113 System.exit(0); 114  }); 115  } 116 117 public void savePreferences() 118  { 119 node.putInt("left", getX()); 120 node.putInt("top", getY()); 121 node.putInt("width", getWidth()); 122 node.putInt("height", getHeight()); 123 node.put("title", getTitle()); 124  } 125 }
复制代码

测试程序4

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

2.掌握基于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 }
复制代码

实验2GUI综合编程练习

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

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

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

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

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

4.查询最小年龄人员信息;

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

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

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

复制代码
 1 package shiwuzhou;
 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 Out { 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 Main1(); 17 frame.setBounds(0, 0,(int)s.getWidth(),(int)s.getHeight()); 18 frame.setTitle("第四组"); 19  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 20 frame.setVisible(true); 21  }); 22  } 23 24 }
复制代码
复制代码
  1 package shiwuzhou;
  2 
  3 import java.awt.BorderLayout;  4 import java.awt.event.ActionEvent;  5 import java.awt.event.ActionListener;  6 import java.io.BufferedReader;  7 import java.io.File;  8 import java.io.FileInputStream;  9 import java.io.FileNotFoundException;  10 import java.io.IOException;  11 import java.io.InputStreamReader;  12 import java.util.*;  13 import java.util.Timer;  14 import javax.swing.*;  15  16 public class Main1 extends JFrame  17 {  18 private static ArrayList<Person> Personlist;  19  20  21 Scanner scanner = new Scanner(System.in);  22 File file = new File("D:\\身份证号.txt");  23  24 private JPanel Panel;  25 private JLabel JLabel1;  26 private JButton Button,Button2,Button3;  27 private JTextArea text,text1,text2,text3;  28 boolean tru=true;  29  30  31  32 public Main1() {  33  34  35 Panel = new JPanel();Panel.setLayout(null);  36 Button = new JButton("1:按姓名字典序输出人员信息");  37 Button2 = new JButton("2:查询最大年龄与最小年龄人员信息");  38 Button3 = new JButton("查询相近年龄");  39 JLabel1 = new JLabel("输入身份证号或者地址查询");  40 JLabel1.setBounds(900, 50, 400, 30);  41  42 text=new JTextArea(30,80);text.setBounds(50, 180, 700, 700);  43 text1=new JTextArea(1,30);text1.setBounds(900, 80, 400, 30);  44 text2=new JTextArea(30,80);text2.setBounds(900,180,700, 700);  45 text3=new JTextArea(30,80);text3.setBounds(420,100,200,40);  46  47 Button.addActionListener(new Action());Button.setBounds(50,50,300,40);  48 Button2.addActionListener(new Action1());Button2.setBounds(50,100,300,40);  49 Button3.addActionListener(new Action2());Button3.setBounds(650,100,120,40);  50  Panel.add(JLabel1);  51  Panel.add(Button);  52  Panel.add(Button2);  53  Panel.add(Button3);  54  Panel.add(text);  55  Panel.add(text2);  56  Panel.add(text1);  57  Panel.add(text3);  58  add(Panel);  59  60  61 Timer timer = new Timer();  62 TimerTask timeTask=new TimerTask() {  63  64  @Override  65 public void run()  66  {  67 // TODO Auto-generated method stub  68 text2.setText(null);  69 String place=text1.getText().toString().trim();  70 for (int i = 0; i <Personlist.size(); i++)  71  {  72  73 String Str=(String)Personlist.get(i).getbirthplace();  74 if(Str.contains(place)&&!place.equals(""))  75  {  76  text2.append(Personlist.get(i).toString());  77  }  78  }  79 for (int i = 0; i <Personlist.size(); i++)  80  {  81  82 String Str=(String)Personlist.get(i).getID();  83 if(Str.contains(place)&&!place.equals(""))  84  {  85  text2.append(Personlist.get(i).toString());  86  }  87  }  88  89  }  90  91 };timer.schedule(timeTask, 0,100);  92  93 Personlist = new ArrayList<>();  94 try {  95 FileInputStream fis = new FileInputStream(file);  96 BufferedReader in = new BufferedReader(new InputStreamReader(fis));  97 String temp = null;  98 while ((temp = in.readLine()) != null) {  99 Scanner linescanner = new Scanner(temp); 100 linescanner.useDelimiter(" "); 101 String name = linescanner.next(); 102 String ID = linescanner.next(); 103 String sex = linescanner.next(); 104 String age = linescanner.next(); 105 String place =linescanner.nextLine(); 106 Person Person = new Person(); 107  Person.setname(name); 108  Person.setID(ID); 109  Person.setsex(sex); 110 int a = Integer.parseInt(age); 111  Person.setage(a); 112  Person.setbirthplace(place); 113  Personlist.add(Person); 114 115  } 116 } catch (FileNotFoundException e) { 117 System.out.println("查找不到信息"); 118  e.printStackTrace(); 119 } catch (IOException e) { 120 System.out.println("信息读取有误"); 121  e.printStackTrace(); 122  } 123 124 125  } 126 127 128 129 130 private class Action implements ActionListener 131  { 132 public void actionPerformed(ActionEvent event) 133  { 134 text.setText(null); 135  Collections.sort(Personlist); 136  text.append(Personlist.toString()); 137  } 138 139  } 140 141 private class Action1 implements ActionListener 142  { 143 public void actionPerformed(ActionEvent event) 144  { 145 text.setText(null); 146 int max=0,min=100;int j,k1 = 0,k2=0; 147 for(int i=1;i<Personlist.size();i++) 148  { 149 j=Personlist.get(i).getage(); 150 if(j>max) 151  { 152 max=j; 153 k1=i; 154  } 155 if(j<min) 156  { 157 min=j; 158 k2=i; 159  } 160  } 161 text.append("年龄最大: "+Personlist.get(k1)+"\n"+"年龄最小: "+Personlist.get(k2)); 162  } 163 164  } 165 166 private class Action2 implements ActionListener 167  { 168 public void actionPerformed(ActionEvent event) 169  { 170 text.setText(null); 171 int a = Integer.parseInt(text3.getText().toString().trim()); 172 int d_value=a-Personlist.get(agenear(a)).getage(); 173 174 for (int i = 0; i < Personlist.size(); i++) 175  { 176 int p=Personlist.get(i).getage()-a; 177 178 if(p==d_value||-p==d_value) text.append(Personlist.get(i).toString()); 179  } 180  } 181 182  } 183 184 185 public static int agenear(int age) { 186 187 int j=0,min=53,d_value=0,k=0; 188 for (int i = 0; i < Personlist.size(); i++) 189  { 190 d_value=Personlist.get(i).getage()-age; 191 if(d_value<0) d_value=-d_value; 192 if (d_value<min) 193  { 194 min=d_value; 195 k=i; 196  } 197 198 } return k; 199 200  } 201 202 }
复制代码
复制代码
 1 package shiwuzhou;
 2 
 3 public class Person implements Comparable<Person> {  4 private String name;  5 private String ID;  6 private int age;  7 private String sex;  8 private String birthplace;  9 10 public String getname() 11 { 12 return name; 13 } 14 public void setname(String name) 15 { 16 this.name = name; 17 } 18 public String getID() 19 { 20 return ID; 21 } 22 public void setID(String ID) 23 { 24 this.ID= ID; 25 } 26 public int getage() 27 { 28 return age; 29 } 30 public void setage(int age) 31 { 32 this.age= age; 33 } 34 public String getsex() 35 { 36 return sex; 37 } 38 public void setsex(String sex) 39 { 40 this.sex= sex; 41 } 42 public String getbirthplace() 43 { 44 return birthplace; 45 } 46 public void setbirthplace(String birthplace) 47 { 48 this.birthplace= birthplace; 49 } 50 51 public int compareTo(Person o) 52 { 53 return this.name.compareTo(o.getname()); 54 } 55 56 public String toString() 57 { 58 return name+"\t"+sex+"\t"+age+"\t"+ID+"\t"+birthplace+"\n"; 59 60 } 61 62 63 64 }
复制代码

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

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

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

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

 

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

 实验总结:

        在这周的实验中主要掌握了界面的布局,也在老师,学长的指导中对生成jar方法有了掌握,以前以为自己在cmd中运行程序没问题,这周老师演示后才发现从前学的都忘完了。看来学的东西还是需要经常的翻阅复习,不然越往后刚开始学的就全忘完了。

猜你喜欢

转载自www.cnblogs.com/zero--/p/10077735.html