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

1、实验目的与要求

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

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

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

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

2、实验内容和步骤

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

测试程序1

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

将所生成的JAR文件移到另外一个不同的目录中,再运行该归档文件,以便确认程序是从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       //获取资源文件
38       URL aboutURL = getClass().getResource("about.gif");
39       Image img = new ImageIcon(aboutURL).getImage();
40       setIconImage(img);
41 
42       JTextArea textArea = new JTextArea();
43       //从当前class下面的路径找文件
44       InputStream stream = getClass().getResourceAsStream("about.txt");
45       //这几句没理解
46       try (Scanner in = new Scanner(stream, "UTF-8"))
47       {
48          while (in.hasNext())
49             textArea.append(in.nextLine() + "\n");
50       }
51       add(textArea);
52    }
53 }
View Code

把JAR文件移动至桌面后运行:

201772020113 李清华《面向对象程序设计(java)》第十五周学习总结_第1张图片

 

掌握创建JAR文件的方法;

 有两种:1.在CMD:

201772020113 李清华《面向对象程序设计(java)》第十五周学习总结_第2张图片

2.用集成开发环境:

右键包->选择导出->Jar文件->照提示下一步即可

 

测试程序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  * 和标题。
 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  * 从属性文件和更新恢复位置和大小的框架。 
 29  * 退出时的属性。 
 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       // 从属性获取位置、大小、标题
 42 
 43       String userDir = System.getProperty("user.home");
 44       File propertiesDir = new File(userDir, ".corejava");
 45       if (!propertiesDir.exists()) propertiesDir.mkdir();
 46       propertiesFile = new File(propertiesDir, "program.properties");
 47 
 48       Properties defaultSettings = new Properties();
 49       defaultSettings.setProperty("left", "0");
 50       defaultSettings.setProperty("top", "0");
 51       defaultSettings.setProperty("width", "" + DEFAULT_WIDTH);
 52       defaultSettings.setProperty("height", "" + DEFAULT_HEIGHT);
 53       defaultSettings.setProperty("title", "");
 54 
 55       settings = new Properties(defaultSettings);
 56 
 57       if (propertiesFile.exists()) 
 58          try (InputStream in = new FileInputStream(propertiesFile))
 59          {         
 60             settings.load(in);
 61          }
 62          catch (IOException ex)
 63          {
 64             ex.printStackTrace();
 65          }
 66 
 67       int left = Integer.parseInt(settings.getProperty("left"));
 68       int top = Integer.parseInt(settings.getProperty("top"));
 69       int width = Integer.parseInt(settings.getProperty("width"));
 70       int height = Integer.parseInt(settings.getProperty("height"));
 71       setBounds(left, top, width, height);
 72 
 73       // 如果没有标题,请询问用户
 74 
 75       String title = settings.getProperty("title");
 76       if (title.equals(""))
 77          title = JOptionPane.showInputDialog("Please supply a frame title:");
 78       if (title == null) title = "";
 79       setTitle(title);
 80       //给窗口注册一个事件监听器
 81       addWindowListener(new WindowAdapter()
 82       {
 83          public void windowClosing(WindowEvent event)
 84          {
 85             settings.setProperty("left", "" + getX());
 86             settings.setProperty("top", "" + getY());
 87             settings.setProperty("width", "" + getWidth());
 88             settings.setProperty("height", "" + getHeight());
 89             settings.setProperty("title", getTitle());
 90             try (OutputStream out = new FileOutputStream(propertiesFile))
 91             {
 92                settings.store(out, "Program Properties");
 93             }
 94             catch (IOException ex)
 95             {
 96                ex.printStackTrace();
 97             }
 98             System.exit(0);
 99          }
100       });
101    }
102 }
View Code

201772020113 李清华《面向对象程序设计(java)》第十五周学习总结_第3张图片

201772020113 李清华《面向对象程序设计(java)》第十五周学习总结_第4张图片

 

测试程序3

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

了解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  * A program to test preference settings. The program remembers the frame
 12  * position, size, and title.
 13  * @version 1.03 2015-06-12
 14  * @author Cay Horstmann
 15  */
 16 public class PreferencesTest
 17 {
 18    public static void main(String[] args)
 19    {
 20       EventQueue.invokeLater(() -> {
 21          PreferencesFrame frame = new PreferencesFrame();
 22          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 23          frame.setVisible(true);
 24       });
 25    }
 26 }
 27 
 28 /**
 29  * A frame that restores position and size from user preferences and updates the
 30  * preferences upon exit.
 31  */
 32 class PreferencesFrame extends JFrame
 33 {
 34    private static final int DEFAULT_WIDTH = 300;
 35    private static final int DEFAULT_HEIGHT = 200;
 36    private Preferences root = Preferences.userRoot();
 37    private Preferences node = root.node("/com/horstmann/corejava");
 38 
 39    public PreferencesFrame()
 40    {
 41       // 从偏好获得位置、大小、标题
 42 
 43       int left = node.getInt("left", 0);
 44       int top = node.getInt("top", 0);
 45       int width = node.getInt("width", DEFAULT_WIDTH);
 46       int height = node.getInt("height", DEFAULT_HEIGHT);
 47       setBounds(left, top, width, height);
 48 
 49       // 如果没有标题,请询问用户
 50 
 51       String title = node.get("title", "");
 52       if (title.equals(""))
 53          title = JOptionPane.showInputDialog("Please supply a frame title:");
 54       if (title == null) title = "";
 55       setTitle(title);
 56 
 57       // 设置显示XML文件的文件选择器
 58 
 59       final JFileChooser chooser = new JFileChooser();
 60       chooser.setCurrentDirectory(new File("."));
 61       chooser.setFileFilter(new FileNameExtensionFilter("XML files", "xml"));
 62 
 63       // 设置菜单
 64 
 65       JMenuBar menuBar = new JMenuBar();
 66       setJMenuBar(menuBar);
 67       JMenu menu = new JMenu("File");
 68       menuBar.add(menu);
 69 
 70       JMenuItem exportItem = new JMenuItem("Export preferences");
 71       menu.add(exportItem);
 72       exportItem
 73             .addActionListener(event -> {
 74                if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)
 75                {
 76                   try
 77                   {
 78                      savePreferences();
 79                      OutputStream out = new FileOutputStream(chooser
 80                            .getSelectedFile());
 81                      node.exportSubtree(out);
 82                      out.close();
 83                   }
 84                   catch (Exception e)
 85                   {
 86                      e.printStackTrace();
 87                   }
 88                }
 89             });
 90 
 91       JMenuItem importItem = new JMenuItem("Import preferences");
 92       menu.add(importItem);
 93       importItem
 94             .addActionListener(event -> {
 95                if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)
 96                {
 97                   try
 98                   {
 99                      InputStream in = new FileInputStream(chooser
100                            .getSelectedFile());
101                      Preferences.importPreferences(in);
102                      in.close();
103                   }
104                   catch (Exception e)
105                   {
106                      e.printStackTrace();
107                   }
108                }
109             });
110 
111       JMenuItem exitItem = new JMenuItem("Exit");
112       menu.add(exitItem);
113       exitItem.addActionListener(event -> {
114          savePreferences();
115          System.exit(0);
116       });
117    }
118    
119    public void savePreferences() 
120    {
121       node.putInt("left", getX());
122       node.putInt("top", getY());
123       node.putInt("width", getWidth());
124       node.putInt("height", getHeight());
125       node.put("title", getTitle());      
126    }
127 }
View Code

201772020113 李清华《面向对象程序设计(java)》第十五周学习总结_第5张图片

201772020113 李清华《面向对象程序设计(java)》第十五周学习总结_第6张图片

 

测试程序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  * A calculator with a calculation history that can be deployed as a Java Web Start application.
 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 }
View Code
  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    A panel with calculator buttons and a result display.
 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       Lays out the panel.
 21    */
 22    public CalculatorPanel()
 23    {  
 24       setLayout(new BorderLayout());
 25 
 26       result = 0;
 27       lastCommand = "=";
 28       start = true;
 29       
 30       // add the display
 31 
 32       display = new JTextArea(10, 20);
 33 
 34       add(new JScrollPane(display), BorderLayout.NORTH);
 35       
 36       ActionListener insert = new InsertAction();
 37       ActionListener command = new CommandAction();
 38 
 39       // add the buttons in a 4 x 4 grid
 40 
 41       panel = new JPanel();
 42       panel.setLayout(new GridLayout(4, 4));
 43 
 44       addButton("7", insert);
 45       addButton("8", insert);
 46       addButton("9", insert);
 47       addButton("/", command);
 48 
 49       addButton("4", insert);
 50       addButton("5", insert);
 51       addButton("6", insert);
 52       addButton("*", command);
 53 
 54       addButton("1", insert);
 55       addButton("2", insert);
 56       addButton("3", insert);
 57       addButton("-", command);
 58 
 59       addButton("0", insert);
 60       addButton(".", insert);
 61       addButton("=", command);
 62       addButton("+", command);
 63 
 64       add(panel, BorderLayout.CENTER);
 65    }
 66 
 67    /**
 68       Gets the history text.
 69       @return the calculator history
 70    */
 71    public String getText()
 72    {
 73       return display.getText();
 74    }
 75    
 76    /**
 77       Appends a string to the history text.
 78       @param s the string to append
 79    */
 80    public void append(String s)
 81    {
 82       display.append(s);
 83    }
 84 
 85    /**
 86       Adds a button to the center panel.
 87       @param label the button label
 88       @param listener the button listener
 89    */
 90    private void addButton(String label, ActionListener listener)
 91    {  
 92       JButton button = new JButton(label);
 93       button.addActionListener(listener);
 94       panel.add(button);
 95    }
 96 
 97    /**
 98       This action inserts the button action string to the
 99       end of the display text.
100    */
101    private class InsertAction implements ActionListener
102    {
103       public void actionPerformed(ActionEvent event)
104       {
105          String input = event.getActionCommand();
106          start = false;
107          display.append(input);
108       }
109    }
110 
111    /**
112       This action executes the command that the button
113       action string denotes.
114    */
115    private class CommandAction implements ActionListener
116    {
117       public void actionPerformed(ActionEvent event)
118       {  
119          String command = event.getActionCommand();
120 
121          if (start)
122          {  
123             if (command.equals("-")) 
124             { 
125                display.append(command); 
126                start = false; 
127             }
128             else 
129                lastCommand = command;
130          }
131          else
132          {  
133             try
134             {
135                int lines = display.getLineCount();
136                int lineStart = display.getLineStartOffset(lines - 1);
137                int lineEnd = display.getLineEndOffset(lines - 1);
138                String value = display.getText(lineStart, lineEnd - lineStart);
139                display.append(" ");
140                display.append(command); 
141                calculate(Double.parseDouble(value));
142                if (command.equals("="))
143                   display.append("\n" + result);
144                lastCommand = command;
145                display.append("\n");
146                start = true;
147             }
148             catch (BadLocationException e)
149             {
150                e.printStackTrace();
151             }
152          }
153       }
154    }
155 
156    /**
157       Carries out the pending calculation. 
158       @param x the value to be accumulated with the prior result.
159    */
160    public void calculate(double x)
161    {
162       if (lastCommand.equals("+")) result += x;
163       else if (lastCommand.equals("-")) result -= x;
164       else if (lastCommand.equals("*")) result *= x;
165       else if (lastCommand.equals("/")) result /= x;
166       else if (lastCommand.equals("=")) result = x;
167    }  
168 }
View Code
  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  * A frame with a calculator panel and a menu to load and save the calculator history.
 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     * Gets the title from the persistent store or asks the user for the title if there is no prior
 56     * entry.
 57     */
 58    public void setTitle()
 59    {
 60       try
 61       {
 62          String title = null;
 63 
 64          BasicService basic = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
 65          URL codeBase = basic.getCodeBase();
 66 
 67          PersistenceService service = (PersistenceService) ServiceManager
 68                .lookup("javax.jnlp.PersistenceService");
 69          URL key = new URL(codeBase, "title");
 70 
 71          try
 72          {
 73             FileContents contents = service.get(key);
 74             InputStream in = contents.getInputStream();
 75             BufferedReader reader = new BufferedReader(new InputStreamReader(in));
 76             title = reader.readLine();
 77          }
 78          catch (FileNotFoundException e)
 79          {
 80             title = JOptionPane.showInputDialog("Please supply a frame title:");
 81             if (title == null) return;
 82 
 83             service.create(key, 100);
 84             FileContents contents = service.get(key);
 85             OutputStream out = contents.getOutputStream(true);
 86             PrintStream printOut = new PrintStream(out);
 87             printOut.print(title);
 88          }
 89          setTitle(title);
 90       }
 91       catch (UnavailableServiceException | IOException e)
 92       {
 93          JOptionPane.showMessageDialog(this, e);
 94       }
 95    }
 96 
 97    /**
 98     * Opens a history file and updates the display.
 99     */
100    public void open()
101    {
102       try
103       {
104          FileOpenService service = (FileOpenService) ServiceManager
105                .lookup("javax.jnlp.FileOpenService");
106          FileContents contents = service.openFileDialog(".", new String[] { "txt" });
107 
108          JOptionPane.showMessageDialog(this, contents.getName());
109          if (contents != null)
110          {
111             InputStream in = contents.getInputStream();
112             BufferedReader reader = new BufferedReader(new InputStreamReader(in));
113             String line;
114             while ((line = reader.readLine()) != null)
115             {
116                panel.append(line);
117                panel.append("\n");
118             }
119          }
120       }
121       catch (UnavailableServiceException e)
122       {
123          JOptionPane.showMessageDialog(this, e);
124       }
125       catch (IOException e)
126       {
127          JOptionPane.showMessageDialog(this, e);
128       }
129    }
130 
131    /**
132     * Saves the calculator history to a file.
133     */
134    public void save()
135    {
136       try
137       {
138          ByteArrayOutputStream out = new ByteArrayOutputStream();
139          PrintStream printOut = new PrintStream(out);
140          printOut.print(panel.getText());
141          InputStream data = new ByteArrayInputStream(out.toByteArray());
142          FileSaveService service = (FileSaveService) ServiceManager
143                .lookup("javax.jnlp.FileSaveService");
144          service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt");
145       }
146       catch (UnavailableServiceException e)
147       {
148          JOptionPane.showMessageDialog(this, e);
149       }
150       catch (IOException e)
151       {
152          JOptionPane.showMessageDialog(this, e);
153       }
154    }
155 }
View Code

这个程序没理解

201772020113 李清华《面向对象程序设计(java)》第十五周学习总结_第7张图片

 

实验2GUI综合编程练习

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

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

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

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

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

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

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

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

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

 1 package practise1;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 public class ButtonTest {
 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 }
View Code
 1 package practise1;
 2 
 3 public class Student implements Comparable {
 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             // int a = Integer.parseInt(age);
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 }
View Code
  1 package practise1;
  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 studentlist;
 19     private static ArrayList list;
 20     private JPanel panel;
 21     private JPanel buttonPanel;
 22     private static final int DEFAULT_WITH = 600;
 23     private static final int DEFAULT_HEIGHT = 300;
 24 
 25     public Main() {
 26         studentlist = new ArrayList<>();
 27         Scanner scanner = new Scanner(System.in);
 28         File file = new File("身份证号.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 jt = new JTextArea();
 63         panel.add(jt);
 64         add(panel, BorderLayout.NORTH);
 65         buttonPanel = new JPanel();
 66         buttonPanel.setLayout(new GridLayout(1, 7));
 67         JButton jButton = new JButton("字典排序");
 68         JButton jButton1 = new JButton("年龄最大和年龄最小");
 69         JLabel lab = new JLabel("猜猜你的老乡");
 70         JTextField jt1 = new JTextField();
 71         JLabel lab1 = new JLabel("找找同龄人(年龄相近):");
 72         JTextField jt2 = new JTextField();
 73         JLabel lab2 = new JLabel("输入你的身份证号码:");
 74         JTextField jt3 = new JTextField();
 75         JButton jButton2 = new JButton("退出");
 76         jButton.setBounds(110, 90, 60, 30);
 77         jButton1.setBounds(110, 90, 60, 30);
 78         jt1.setBounds(110, 90, 60, 30);
 79         jt2.setBounds(110, 90, 60, 30);
 80         jt3.setBounds(110, 90, 60, 30);
 81         jButton2.setBounds(110, 90, 60, 30);
 82         jButton.addActionListener(new ActionListener() {
 83             public void actionPerformed(ActionEvent e) {
 84                 Collections.sort(studentlist);
 85                 jt.setText(studentlist.toString());
 86             }
 87         });
 88         jButton1.addActionListener(new ActionListener() {
 89             public void actionPerformed(ActionEvent e) {
 90                 int max = 0, min = 100;
 91                 int j, k1 = 0, k2 = 0;
 92                 for (int i = 1; i < studentlist.size(); i++) {
 93                     j = studentlist.get(i).getage();
 94                     if (j > max) {
 95                         max = j;
 96                         k1 = i;
 97                     }
 98                     if (j < min) {
 99                         min = j;
100                         k2 = i;
101                     }
102 
103                 }
104                 jt.setText("年龄最大:" + studentlist.get(k1) + "年龄最小:" + studentlist.get(k2));
105             }
106         });
107         jButton2.addActionListener(new ActionListener() {
108             public void actionPerformed(ActionEvent e) {
109                 dispose();
110                 System.exit(0);
111             }
112         });
113         jt1.addActionListener(new ActionListener() {
114             public void actionPerformed(ActionEvent e) {
115                 String find = jt1.getText();
116                 String text="";
117                 String place = find.substring(0, 3);
118                 for (int i = 0; i < studentlist.size(); i++) {
119                     if (studentlist.get(i).getprovince().substring(1, 4).equals(place)) {
120                         text+="\n"+studentlist.get(i);
121                         jt.setText("老乡:" + text);
122                     }
123                 }
124             }
125         });
126         jt2.addActionListener(new ActionListener() {
127             public void actionPerformed(ActionEvent e) {
128                 String yourage = jt2.getText();
129                 int a = Integer.parseInt(yourage);
130                 int near = agenear(a);
131                 int value = a - studentlist.get(near).getage();
132                 jt.setText("年龄相近:" + studentlist.get(near));
133             }
134         });
135         jt3.addActionListener(new ActionListener() {
136             public void actionPerformed(ActionEvent e) {
137                 list = new ArrayList<>();
138                 Collections.sort(studentlist);
139                 String key = jt3.getText();
140                 for (int i = 1; i < studentlist.size(); i++) {
141                     if (studentlist.get(i).getnumber().contains(key)) {                        
142                         list.add(studentlist.get(i));                        
143                         jt.setText("emmm!你可能是:\n" + list);
144                         //System.out.println("可能的人:" + studentlist.get(i));
145                         //jt.setText("可能的人:" + studentlist.get(i));
146                     }                    
147                 }
148             }
149         });
150         buttonPanel.add(jButton);
151         buttonPanel.add(jButton1);
152         buttonPanel.add(lab);
153         buttonPanel.add(jt1);
154         buttonPanel.add(lab1);
155         buttonPanel.add(jt2);
156         buttonPanel.add(lab2);
157         buttonPanel.add(jt3);
158         buttonPanel.add(jButton2);
159         add(buttonPanel, BorderLayout.SOUTH);
160         setSize(DEFAULT_WITH, DEFAULT_HEIGHT);
161     }
162 
163     public static int agenear(int age) {
164         int min = 53, value = 0, k = 0;
165         for (int i = 0; i < studentlist.size(); i++) {
166             value = studentlist.get(i).getage() - age;
167             if (value < 0)
168                 value = -value;
169             if (value < min) {
170                 min = value;
171                 k = i;
172             }
173         }
174         return k;
175     }
176 
177 }
View Code

201772020113 李清华《面向对象程序设计(java)》第十五周学习总结_第8张图片

201772020113 李清华《面向对象程序设计(java)》第十五周学习总结_第9张图片

 

 

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

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

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

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

 

你可能感兴趣的:(201772020113 李清华《面向对象程序设计(java)》第十五周学习总结)