zoukankan      html  css  js  c++  java
  • 201771010134杨其菊《面向对象程序设计(java)》第十五周学习

                                                                                               第十五周学习总结

     第一部分:理论知识

     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() + "
    ");
    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
    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应用程序的发布方法。

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

     没有调试成功

    实验2GUI综合编程练习

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

    练习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 }
    package AA;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStreamReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Scanner;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
    public class Main extends JFrame {
        private static ArrayList<Student> studentlist;
        private static ArrayList<Student> list;
        private JPanel panel;
        private JPanel buttonPanel;
        private static final int DEFAULT_WITH = 900;
        private static final int DEFAULT_HEIGHT = 600;
    
        public Main() {
            studentlist = new ArrayList<>();
            Scanner scanner = new Scanner(System.in);
            File file = new File("G:\身份证号.txt");
            try {
                FileInputStream fis = new FileInputStream(file);
                BufferedReader in = new BufferedReader(new InputStreamReader(fis));
                String temp = null;
                while ((temp = in.readLine()) != null) {
    
                    Scanner linescanner = new Scanner(temp);
    
                    linescanner.useDelimiter(" ");
                    String name = linescanner.next();
                    String number = linescanner.next();
                    String sex = linescanner.next();
                    String age = linescanner.next();
                    String province = linescanner.nextLine();
                    Student student = new Student();
                    student.setName(name);
                    student.setnumber(number);
                    student.setsex(sex);
                    int a = Integer.parseInt(age);
                    student.setage(a);
                    student.setprovince(province);
                    studentlist.add(student);
    
                }
            } catch (FileNotFoundException e) {
                System.out.println("文件找不到");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("文件读取错误");
                e.printStackTrace();
            }
            panel = new JPanel();
            panel.setLayout(new BorderLayout());
            JTextArea A = new JTextArea();
            panel.add(A);
            add(panel, BorderLayout.NORTH);
            buttonPanel = new JPanel();
            
            buttonPanel.setLayout(new GridLayout(6, 2));
            JButton jButton = new JButton("字典排序");
            JButton jButton1 = new JButton("年龄最大和年龄最小");
            JLabel lab1 = new JLabel("寻找你的老乡");
            JTextField a1 = new JTextField();
            JLabel lab2 = new JLabel("寻找找同龄人:");
            JTextField a2 = new JTextField();
            JLabel lab3 = new JLabel("输入身份证号码查询信息:");
            JTextField a3 = new JTextField();
            JButton jButton2 = new JButton("退出");
            
            jButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    Collections.sort(studentlist);
                    A.setText(studentlist.toString());
                }
            });
            jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    int max = 0, min = 100;
                    int j, k1 = 0, k2 = 0;
                    for (int i = 1; i < studentlist.size(); i++) {
                        j = studentlist.get(i).getage();
                        if (j > max) {
                            max = j;
                            k1 = i;
                        }
                        if (j < min) {
                            min = j;
                            k2 = i;
                        }
    
                    }
                   A.setText("年龄最大:" + studentlist.get(k1) + "年龄最小:" + studentlist.get(k2));
                }
            });
            jButton2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dispose();
                    System.exit(0);
                }
            });
            a1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    String find = a1.getText();
                    String text="";
                    String place = find.substring(0, 3);
                    for (int i = 0; i < studentlist.size(); i++) {
                        if (studentlist.get(i).getprovince().substring(1, 4).equals(place)) {
                            text+="
    "+studentlist.get(i);
                            A.setText("老乡:" + text);
                        }
                    }
                }
            });
            a2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    String yourage = a2.getText();
                    int a = Integer.parseInt(yourage);
                    int near = agenear(a);
                    int value = a - studentlist.get(near).getage();
                    A.setText("年龄相近:" + studentlist.get(near));
                }
            });
            a3.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    list = new ArrayList<>();
                    Collections.sort(studentlist);
                    String key = a3.getText();
                    for (int i = 1; i < studentlist.size(); i++) {
                        if (studentlist.get(i).getnumber().contains(key)) {                        
                            list.add(studentlist.get(i));                        
                            A.setText("结果:
    " + list);
                            
                        }                    
                    }
                }
            });
            buttonPanel.add(jButton);
            buttonPanel.add(jButton1);
            buttonPanel.add(lab1);
            buttonPanel.add(a1);
            buttonPanel.add(lab2);
            buttonPanel.add(a2);
            buttonPanel.add(lab3);
            buttonPanel.add(a3);
            buttonPanel.add(jButton2);
            add(buttonPanel, BorderLayout.SOUTH);
            setSize(DEFAULT_WITH, DEFAULT_HEIGHT);
        }
    
        public static int agenear(int age) {
            int min = 53, value = 0, k = 0;
            for (int i = 0; i < studentlist.size(); i++) {
                value = studentlist.get(i).getage() - age;
                if (value < 0)
                    value = -value;
                if (value < min) {
                    min = value;
                    k = i;
                }
            }
            return k;
        }
    
    }
    package AA;
    
    public class Student implements Comparable<Student> {
    
        private String name;
        private String number ;
        private String sex ;
        private int age;
        private String province;
       
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getnumber() {
            return number;
        }
        public void setnumber(String number) {
            this.number = number;
        }
        public String getsex() {
            return sex ;
        }
        public void setsex(String sex ) {
            this.sex =sex ;
        }
        public int getage() {
    
            return age;
            }
            public void setage(int age) {
               
            this.age= age;
            }
    
        public String getprovince() {
            return province;
        }
        public void setprovince(String province) {
            this.province=province ;
        }
    
        public int compareTo(Student o) {
           return this.name.compareTo(o.getName());
        }
    
        public String toString() {
            return  name+"	"+sex+"	"+age+"	"+number+"	"+province+"
    ";
        }    
    }

                

          

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

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

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

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

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

     

    第三部分:

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

  • 相关阅读:
    Oracle——oem开启managementserver的时候搜索不到节点的解决方法!!!
    PL/SQL学习笔记(一)
    oracle 数据库的非指令备份方法
    OracleDBConsole[SID]服务简介
    Toad 使用快速入门
    oracle 配置
    sql中exist与in 的区别
    页面之间传递参数的几种方法荟萃
    div+CSS网页布局入门系列教程(来自标准之路)
    XML操作类
  • 原文地址:https://www.cnblogs.com/yqj-yf-111/p/10090204.html
Copyright © 2011-2022 走看看