zoukankan      html  css  js  c++  java
  • 达拉草201771010105《面向对象程序设计(java)》第十五周学习总结

    达拉草201771010105《面向对象程序设计(java)》第十四周学习总结

    第一部分:理论知识

    JAR文件:

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

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

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

    jar命令:

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

    (1) 创建JAR文件

    jar cf jar-file input-file(s) c---want to Create a JAR file. 

    (2) 查看JAR文件

    jar tf jar-file t---want to view the Table of contents of the JAR file.

    (3) 提取JAR文件

    jar xf jar-file [archived-file(s)] x---want to extract files from the JAR archive. 

    (4) 更新JAR文件

    jar uf jar-file input-file(s) u---want to update an existing JAR file. 

    (5) 索引JAR文件 

    jar i jar-file i---index an existing JAR file. 

    清单文件:

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

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

    运行JAR文件

    1.用户可以通过下面的命令来启动应用程序: java –jar MyProgram.jar.

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

    资源:

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

    (1)图像和声音文件。

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

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

     编译、创建JAR文件和执行这个程序的命令如下:

    – javac ResourceTest.java

    – jar cvfm ResourceTest.jar ResourceTest.mf *.class *.gif *.txt – java –jar ResourceTest.jar

    Eclipse导出JAR文件:

    (1)工程没有引用外部jar包时,直接导出。
    (2)当工程引用了其他的外部jar时,由于Eclipse 不支持同时导出外部jar包的功能,导出过程比 较复杂。

    Java Web Start:

    (1)Java Web Start是一个用Java编写的应用程序,它是Sun 公司推出的一项在Internet上发布应用程序的技术;

    (2)通过Java Web Start可以使一个应用程序很容易地通过 web部署在各个平台上,包括Windows,Linux,Solaris等。

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

    实验时间 2018-12-6

    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 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  * A frame that loads image and text resources.
    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();//根据指定的 URL 创建一个 ImageIcon
    39       setIconImage(img);//设置要作为此窗口图标显示的图像。
    40 
    41       JTextArea textArea = new JTextArea();//创建新的 TextArea
    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() + "
    ");
    47          //将给定文本追加到文档结尾。如果模型为 null 或者字符串为 null 或空,则不执行任何操作。 
    48       }
    49       add(textArea);
    50    }
    51 }

    运行结果如下:

                             

    测试程序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  * A program to test properties. The program remembers the frame position, size,
     12  * and title.
     13  * @version 1.01 2015-06-16
     14  * @author Cay Horstmann
     15  */
     16 public class PropertiesTest
     17 {
     18    public static void main(String[] args)
     19    {
     20       EventQueue.invokeLater(() -> {
     21          PropertiesFrame frame = new PropertiesFrame();
     22          frame.setVisible(true);
     23       });
     24    }
     25 }
     26 
     27 /**
     28  * A frame that restores position and size from a properties file and updates
     29  * the properties upon exit.
     30  */
     31 class PropertiesFrame extends JFrame
     32 {
     33    private static final int DEFAULT_WIDTH = 300;
     34    private static final int DEFAULT_HEIGHT = 200;
     35 
     36    private File propertiesFile;
     37    private Properties settings;
     38 
     39    public PropertiesFrame()
     40    {
     41      // 从属性中获取位置、大小和标题
     42 
     43 
     44       String userDir = System.getProperty("user.home");
     45       File propertiesDir = new File(userDir, ".corejava");
     46       if (!propertiesDir.exists()) propertiesDir.mkdir();
     47       propertiesFile = new File(propertiesDir, "program.properties");
     48 
     49       Properties defaultSettings = new Properties();
     50       defaultSettings.setProperty("left", "0");
     51       defaultSettings.setProperty("top", "0");
     52       defaultSettings.setProperty("width", "" + DEFAULT_WIDTH);
     53       defaultSettings.setProperty("height", "" + DEFAULT_HEIGHT);
     54       defaultSettings.setProperty("title", "");
     55 
     56       settings = new Properties(defaultSettings);
     57 
     58       if (propertiesFile.exists()) 
     59          try (InputStream in = new FileInputStream(propertiesFile))
     60          {         
     61             settings.load(in);
     62          }
     63          catch (IOException ex)
     64          {
     65             ex.printStackTrace();
     66          }
     67 
     68       int left = Integer.parseInt(settings.getProperty("left"));
     69       int top = Integer.parseInt(settings.getProperty("top"));
     70       int width = Integer.parseInt(settings.getProperty("width"));
     71       int height = Integer.parseInt(settings.getProperty("height"));
     72       setBounds(left, top, width, height);
     73 
     74       // 如果没有标题,询问用户
     75 
     76 
     77       String title = settings.getProperty("title");
     78       if (title.equals(""))//将此字符串与指定的对象比较。
     79          title = JOptionPane.showInputDialog("Please supply a frame title:");
     80       if (title == null) title = "";
     81       setTitle(title);
     82       //添加指定的窗口侦听器,以从此窗口接收窗口事件。
     83       addWindowListener(new WindowAdapter()
     84       {
     85          public void windowClosing(WindowEvent event)
     86          {
     87             settings.setProperty("left", "" + getX());
     88             settings.setProperty("top", "" + getY());
     89             settings.setProperty("width", "" + getWidth());
     90             settings.setProperty("height", "" + getHeight());
     91             settings.setProperty("title", getTitle());
     92             try (OutputStream out = new FileOutputStream(propertiesFile))//创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
     93             {
     94                settings.store(out, "Program Properties");
     95             }
     96             catch (IOException ex)
     97             {
     98                ex.printStackTrace();
     99             }
    100             System.exit(0);//终止当前正在运行的 Java 虚拟机。
    101          }
    102       });
    103    }
    104 }

    运行结果如下:

       

    测试程序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          //显示请求用户输入的问题消息对话框。
     55       if (title == null) title = "";
     56       setTitle(title);
     57 
     58       // 设置显示XML文件的文件选择器
     59 
     60       final JFileChooser chooser = new JFileChooser();
     61       chooser.setCurrentDirectory(new File("."));//设置当前目录
     62       chooser.setFileFilter(new FileNameExtensionFilter("XML files", "xml"));
     63       //使用指定的描述和文件扩展名创建一个 FileNameExtensionFilter
     64 
     65       // 设置菜单
     66 
     67       JMenuBar menuBar = new JMenuBar();//创建菜单栏
     68       setJMenuBar(menuBar);//设置此窗体的菜单栏。 
     69       JMenu menu = new JMenu("File");//构造一个新 JMenu,用提供的字符串作为其文本。 
     70       menuBar.add(menu);
     71 
     72       JMenuItem exportItem = new JMenuItem("Export preferences");
     73       menu.add(exportItem);
     74       exportItem
     75             .addActionListener(event -> { 
     76                if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)
     77                {
     78                   try
     79                   {
     80                      savePreferences();
     81                      OutputStream out = new FileOutputStream(chooser
     82                            .getSelectedFile());
     83                      node.exportSubtree(out);
     84                      out.close();
     85                   }
     86                   catch (Exception e)
     87                   {
     88                      e.printStackTrace();
     89                   }
     90                }
     91             });
     92 
     93       JMenuItem importItem = new JMenuItem("Import preferences");
     94       menu.add(importItem);
     95       importItem
     96             .addActionListener(event -> {
     97                if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION)
     98                {//JFileChooser 为用户选择文件提供了一种简单的机制。
     99                   try
    100                   {
    101                      InputStream in = new FileInputStream(chooser
    102                            .getSelectedFile());
    103                      Preferences.importPreferences(in);
    104                      in.close();
    105                   }
    106                   catch (Exception e)
    107                   {
    108                      e.printStackTrace();
    109                   }
    110                }
    111             });
    112 
    113       JMenuItem exitItem = new JMenuItem("Exit");
    114       menu.add(exitItem);
    115       exitItem.addActionListener(event -> {
    116          savePreferences();
    117          System.exit(0);
    118       });
    119    }
    120    
    121    public void savePreferences() 
    122    {
    123       node.putInt("left", getX());
    124       node.putInt("top", getY());
    125       node.putInt("width", getWidth());
    126       node.putInt("height", getHeight());
    127       node.put("title", getTitle());      
    128    }
    129 }

    运行结果如下:

         

    测试程序4

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

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

      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       // 添加显示
     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       // 在4×4网格中添加按钮
     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("
    " + result);
    144                lastCommand = command;
    145                display.append("
    ");
    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 }
      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());//调出标题为 "Message" 的信息消息对话框。 
    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("
    ");
    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 }
     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 }

    实验2GUI综合编程练习

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

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

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

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

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

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

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

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

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

      1 package 身份证;
      2 import java.io.BufferedReader;
      3 
      4 import java.io.FileNotFoundException;
      5 import java.io.FileReader;
      6 import java.io.IOException;
      7 import java.util.ArrayList;
      8 //import java.util.Arrays;
      9 import java.util.Collections;
     10 import java.util.Scanner;
     11 import java.util.TimerTask;
     12 
     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<Student> list;
     20     private JPanel buttonPanel;
     21  //   private JPanel panel;
     22     
     23     Scanner scanner = new Scanner(System.in);
     24    
     25     public Main() {
     26          studentlist = new ArrayList<>();
     27            
     28             
     29    //    Timer timer=new Timer();
     30          JTextArea jt = new JTextArea();
     31          jt.setBounds(520, 100, 800, 600);
     32          buttonPanel = new JPanel();
     33        
     34          JButton jButton = new JButton("1.字典排序:");
     35          JButton jButton1 = new JButton("2.年龄最大和年龄最小:");
     36          JLabel lab = new JLabel("3.猜猜你的老乡:");
     37          JTextField jt1 = new JTextField();
     38          JLabel lab1 = new JLabel("4.找找同龄人(年龄相近):");
     39          JTextField jt2 = new JTextField();
     40          JLabel lab2 = new JLabel("5.输入你的身份证号码:");
     41          JTextField jt3 = new JTextField();
     42          JButton jButton2 = new JButton("6.退出");
     43          buttonPanel. setLayout(null);
     44          jButton.setBounds(50, 160, 100, 30);
     45          jButton1.setBounds(50, 220, 160, 30);
     46          lab2.setBounds(50, 400, 100, 30);
     47          lab.setBounds(50, 280, 150, 30);
     48          jt1.setBounds(150, 280, 100, 30);
     49          lab1.setBounds(50, 340, 150, 30);
     50          jt2.setBounds(200, 340, 160, 30);
     51          jt3.setBounds(200, 400, 160, 30);
     52          jButton2.setBounds(50, 460, 60, 30);
     53          buttonPanel.add(jButton);
     54          buttonPanel.add(jButton1);
     55          buttonPanel.add(lab);
     56          buttonPanel.add(jt1);
     57          buttonPanel.add(lab1);
     58          buttonPanel.add(jt2);
     59          buttonPanel.add(lab2);
     60          buttonPanel.add(jt3);
     61          buttonPanel.add(jButton2);
     62          add(buttonPanel);
     63          buttonPanel.add(jt);
     64        
     65         try {
     66             
     67             BufferedReader in = new BufferedReader(new FileReader("身份证号.txt"));
     68             String temp = null;
     69             while ((temp = in.readLine()) != null) {
     70 
     71                 Scanner linescanner = new Scanner(temp);
     72 
     73                 linescanner.useDelimiter(" ");
     74                 String name = linescanner.next();
     75                 String number = linescanner.next();
     76                 String sex = linescanner.next();
     77                 String age = linescanner.next();
     78                 String province = linescanner.nextLine();
     79                 Student student = new Student();
     80                 student.setName(name);
     81                 student.setnumber(number);
     82                 student.setsex(sex);
     83                 int a = Integer.parseInt(age);
     84                 student.setage(a);
     85                 student.setprovince(province);
     86                 studentlist.add(student);
     87 
     88             }
     89         } catch (FileNotFoundException e) {
     90             System.out.println("学生信息文件找不到");
     91             e.printStackTrace();
     92         } catch (IOException e) {
     93             System.out.println("学生信息文件读取错误");
     94             e.printStackTrace();
     95         }
     96    
     97         
     98     jButton.addActionListener(new ActionListener() {
     99              
    100           public void actionPerformed(ActionEvent e) {
    101                  jt.setText(null);
    102                 Collections.sort(studentlist);
    103                jt.setText(studentlist.toString());
    104                // jt.append(studentlist.toString());
    105             }
    106              
    107         });
    108         jButton1.addActionListener(new ActionListener() {
    109             public void actionPerformed(ActionEvent e) {
    110                 int max = 0, min = 100;
    111                 int j, k1 = 0, k2 = 0;
    112                 for (int i = 1; i < studentlist.size(); i++) {
    113                     j = ((Student) studentlist.get(i)).getage();
    114                     if (j > max) {
    115                         max = j;
    116                         k1 = i;
    117                     }
    118                     if (j < min) {
    119                         min = j;
    120                         k2 = i;
    121                     }
    122 
    123                 }
    124                 jt.setText("年龄最大:" + studentlist.get(k1) + "年龄最小:" + studentlist.get(k2));
    125             }
    126         });
    127         jButton2.addActionListener(new ActionListener() {
    128             public void actionPerformed(ActionEvent e) {
    129                 dispose();
    130                 System.exit(0);
    131             }
    132         });
    133         jt1.addActionListener(new ActionListener() {
    134             public void actionPerformed(ActionEvent e) {
    135                 String find = jt1.getText();
    136                 String text="";
    137                 String place = find.substring(0, 3);
    138                 for (int i = 0; i < studentlist.size(); i++) {
    139                     if (((Student) studentlist.get(i)).getprovince().substring(1, 4).equals(place)) {
    140                         text+="
    "+studentlist.get(i);
    141                         jt.setText("老乡:" + text);
    142                     }
    143                 }
    144             }
    145         });
    146         jt2.addActionListener(new ActionListener() {
    147             public void actionPerformed(ActionEvent e) {
    148                 String yourage = jt2.getText();
    149                 int a = Integer.parseInt(yourage);
    150                 int near = agenear(a);
    151                 int value = a - ((Student) studentlist.get(near)).getage();
    152                 jt.setText("年龄相近:" + studentlist.get(near));
    153             }
    154         });
    155         jt3.addKeyListener(new KeyAdapter() {
    156          
    157            
    158                 public void keyTyped(KeyEvent e) {
    159                 list = new ArrayList<>();
    160                 Collections.sort(studentlist);
    161                 String key = jt3.getText();
    162                 for (int i = 1; i < studentlist.size(); i++) {
    163                     if (((Student) studentlist.get(i)).getnumber().contains(key)) {                        
    164                         list.add((Student) studentlist.get(i));                        
    165                         jt.setText("你可能是:
    " + list);
    166                         
    167                         
    168                     }                    
    169                 }
    170             }
    171 
    172         });
    173       
    174       
    175         
    176         
    177      
    178     }
    179 
    180     public static int agenear(int age) {
    181         int min = 53, value = 0, k = 0;
    182         for (int i = 0; i < studentlist.size(); i++) {
    183             value = ((Student) studentlist.get(i)).getage() - age;
    184             if (value < 0)
    185                 value = -value;
    186             if (value < min) {
    187                 min = value;
    188                 k = i;
    189             }
    190         }
    191         return k;
    192     }
    193    
    194 
    195     }
     1 package 身份证;
     2 import java.awt.*;
     3 import javax.swing.*;
     4  
     5 /**
     6  * @version 1.34 2015-06-12
     7  * @author Cay Horstmann
     8  */
     9 public class demo1
    10 {
    11    public static void main(String[] args)
    12    {
    13       EventQueue.invokeLater(() -> {
    14          JFrame frame = new Main();
    15          frame.setTitle("查询");
    16          frame.setBounds(500, 50, 500, 500);
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);
    19       });
    20    }
    21 }
     1 package 身份证;
     2 public  class Student  implements Comparable<Student> {
     3 
     4     private String name;
     5     private String number ;
     6     private String sex ;
     7     private int age;
     8     private String province;
     9    
    10     public String getName() {
    11         return name;
    12     }
    13     public void setName(String name) {
    14         this.name = name;
    15     }
    16     public String getnumber() {
    17         return number;
    18     }
    19     public void setnumber(String number) {
    20         this.number = number;
    21     }
    22     public String getsex() {
    23         return sex ;
    24     }
    25     public void setsex(String sex ) {
    26         this.sex =sex ;
    27     }
    28     public int getage() {
    29 
    30         return age;
    31         }
    32         public void setage(int age) {
    33            
    34         this.age= age;
    35         }
    36 
    37     public String getprovince() {
    38         return province;
    39     }
    40     public void setprovince(String province) {
    41         this.province=province ;
    42     }
    43 
    44     public int compareTo(Student o) {
    45        return this.name.compareTo(o.getName());
    46     }
    47 
    48     public String toString() {
    49         return  name+"	"+sex+"	"+age+"	"+number+"	"+province+"
    ";
    50     }
    51     
    52 }

    运行结果如下:

             

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

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

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

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

     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 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 shiwuzhou;
      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 }

     运行结果如下:

           

     实验总结:

            在本周的 学习中我们学了第十三章的部署应用知识,JRA文件的应用,它除了类文件,图像和其他资源外,还包含一个用用于描述归档特征的清单文件,通过验证实验测试,结合运行结果大概理解了本周的相关知识,比如属性,资源等。这周实验的难点就是最后的两个编程题,尤其是第一个编程的模糊查找。

  • 相关阅读:
    15. DML, DDL, LOGON 触发器
    5. 跟踪标记 (Trace Flag) 834, 845 对内存页行为的影响
    4. 跟踪标记 (Trace Flag) 610 对索引组织表(IOT)最小化日志
    14. 类似正则表达式的字符处理问题
    01. SELECT显示和PRINT打印超长的字符
    3. 跟踪标记 (Trace Flag) 1204, 1222 抓取死锁信息
    2. 跟踪标记 (Trace Flag) 3604, 3605 输出DBCC命令结果
    1. 跟踪标记 (Trace Flag) 1117, 1118 文件增长及空间分配方式
    0. 跟踪标记 (Trace Flag) 简介
    SpringBoot + Redis + Shiro 实现权限管理(转)
  • 原文地址:https://www.cnblogs.com/dalacao/p/10090259.html
Copyright © 2011-2022 走看看