孔维滢 20171010110《面向对象程序设计(java)》第十五周学习总结

Posted weiron

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了孔维滢 20171010110《面向对象程序设计(java)》第十五周学习总结相关的知识,希望对你有一定的参考价值。

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

1、实验目的与要求

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

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

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

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

2、实验内容和步骤

实验1:

测试程序1

package resource;

import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;

/**
 * @version 1.41 2015-06-12
 * @author Cay Horstmann
 */
public class ResourceTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         JFrame frame = new ResourceTestFrame();//构建一个ResourceTestFrame类对象
         frame.setTitle("ResourceTest");//设置Title属性,确定框架标题栏中的文字
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭操作,退出并关闭
         frame.setVisible(true);//设置Visible属性,组件可见
      });
   }
}

/**
 * A frame that loads image and text resources.
 */
class ResourceTestFrame extends JFrame
{
   private static final int DEFAULT_WIDTH = 300;
   private static final int DEFAULT_HEIGHT = 300;

   public ResourceTestFrame()
   {
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      //利用about.gif图像文件制作图标
      URL aboutURL = getClass().getResource("about.gif");
      Image img = new ImageIcon(aboutURL).getImage();
      //在找到ResourceTest类的地方查找about.gif文件
      setIconImage(img);

      JTextArea textArea = new JTextArea();
      //读取about.txt文件
      InputStream stream = getClass().getResourceAsStream("about.txt");
      try (Scanner in = new Scanner(stream, "UTF-8"))
      {
         while (in.hasNext())
            textArea.append(in.nextLine() + "
");
      }
      add(textArea);
   }
}

  技术分享图片

测试程序2

package properties;

import java.awt.EventQueue;
import java.awt.event.*;
import java.io.*;
import java.util.Properties;

import javax.swing.*;

/**
 * A program to test properties. The program remembers the frame position, size,
 * and title.
 * @version 1.01 2015-06-16
 * @author Cay Horstmann
 */
public class PropertiesTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() 
    		  -> {
         PropertiesFrame frame = new PropertiesFrame();
         frame.setVisible(true);
      });
   }
}

/**
 * A frame that restores position and size from a properties file and updates
 * the properties upon exit.
 */
class PropertiesFrame extends JFrame
{
   private static final int DEFAULT_WIDTH = 300;
   private static final int DEFAULT_HEIGHT = 200;

   private File propertiesFile;
   private Properties settings;

   public PropertiesFrame()
   {
      // 从属性中获取位置、大小和标题

      String userDir = System.getProperty("user.home");
      File propertiesDir = new File(userDir, ".corejava");
      if (!propertiesDir.exists()) propertiesDir.mkdir();
      propertiesFile = new File(propertiesDir, "program.properties");

      Properties defaultSettings = new Properties();
      defaultSettings.setProperty("left", "0");
      defaultSettings.setProperty("top", "0");
      defaultSettings.setProperty("width", "" + DEFAULT_WIDTH);
      defaultSettings.setProperty("height", "" + DEFAULT_HEIGHT);
      defaultSettings.setProperty("title", "");

      settings = new Properties(defaultSettings);

      if (propertiesFile.exists()) 
         try (InputStream in = new FileInputStream(propertiesFile))
         {         
            settings.load(in);
         }
         catch (IOException ex)
         {
            ex.printStackTrace();
         }

      int left = Integer.parseInt(settings.getProperty("left"));
      int top = Integer.parseInt(settings.getProperty("top"));
      int width = Integer.parseInt(settings.getProperty("width"));
      int height = Integer.parseInt(settings.getProperty("height"));
      setBounds(left, top, width, height);

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

      String title = settings.getProperty("title");
      if (title.equals(""))
         title = JOptionPane.showInputDialog("Please supply a frame title:");
      if (title == null) title = "";
      setTitle(title);

      //添加指定的窗口侦听器,以从此窗口接收窗口事件。
      addWindowListener(new WindowAdapter()
      {
         public void windowClosing(WindowEvent event)
         {
            settings.setProperty("left", "" + getX());
            settings.setProperty("top", "" + getY());
            settings.setProperty("width", "" + getWidth());
            settings.setProperty("height", "" + getHeight());
            settings.setProperty("title", getTitle());
            try (OutputStream out = new FileOutputStream(propertiesFile))
            {
               settings.store(out, "Program Properties");
            }
            catch (IOException ex)
            {
               ex.printStackTrace();
            }
            System.exit(0);
         }
      });
   }
}

  技术分享图片技术分享图片

测试程序3

package preferences;

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

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

/**
 * A program to test preference settings. The program remembers the frame
 * position, size, and title.
 * @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);
      });
   }
}

/**
 * A frame that restores position and size from user preferences and updates the
 * preferences upon exit.
 */
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

package webstart;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

/**
   带有计算器按钮和结果显示的面板。
*/
public class CalculatorPanel extends JPanel
{  
   private JTextArea display;
   private JPanel panel;
   private double result;
   private String lastCommand;
   private boolean start;

   /**
       布置面板。
   */
   public CalculatorPanel()
   {  
      setLayout(new BorderLayout());

      result = 0;
      lastCommand = "=";
      start = true;
      
      // 添加显示

      display = new JTextArea(10, 20);

      add(new JScrollPane(display), BorderLayout.NORTH);
      
      ActionListener insert = new InsertAction();
      ActionListener command = new CommandAction();

      // 在一个4×4的网格中添加按钮

      panel = new JPanel();
      panel.setLayout(new GridLayout(4, 4));

      addButton("7", insert);
      addButton("8", insert);
      addButton("9", insert);
      addButton("/", command);

      addButton("4", insert);
      addButton("5", insert);
      addButton("6", insert);
      addButton("*", command);

      addButton("1", insert);
      addButton("2", insert);
      addButton("3", insert);
      addButton("-", command);

      addButton("0", insert);
      addButton(".", insert);
      addButton("=", command);
      addButton("+", command);

      add(panel, BorderLayout.CENTER);
   }

   /**
       获取历史文本。
      @return the calculator history
   */
   public String getText()
   {
      return display.getText();
   }
   
   /**
       向历史文本追加字符串。
      @param s the string to append
   */
   public void append(String s)
   {
      display.append(s);
   }

   /**
       向中心面板添加一个按钮。
      @param label the button label
      @param listener the button listener
   */
   private void addButton(String label, ActionListener listener)
   {  
      JButton button = new JButton(label);
      button.addActionListener(listener);
      panel.add(button);
   }

   /**
      此操作将按钮操作字符串插入到显示文本的末尾。
   */
   private class InsertAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         String input = event.getActionCommand();
         start = false;
         display.append(input);
      }
   }

   /**
       该操作执行按钮操作字符串表示的命令。
   */
   private class CommandAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {  
         String command = event.getActionCommand();

         if (start)
         {  
            if (command.equals("-")) 
            { 
               display.append(command); 
               start = false; 
            }
            else 
               lastCommand = command;
         }
         else
         {  
            try
            {
               int lines = display.getLineCount();
               int lineStart = display.getLineStartOffset(lines - 1);
               int lineEnd = display.getLineEndOffset(lines - 1);
               String value = display.getText(lineStart, lineEnd - lineStart);
               display.append(" ");
               display.append(command); 
               calculate(Double.parseDouble(value));
               if (command.equals("="))
                  display.append("
" + result);
               lastCommand = command;
               display.append("
");
               start = true;
            }
            catch (BadLocationException e)
            {
               e.printStackTrace();
            }
         }
      }
   }

   /**
          执行暂挂计算。
      @param x与先前结果累积的值。
   */
   public void calculate(double x)
   {
      if (lastCommand.equals("+")) result += x;
      else if (lastCommand.equals("-")) result -= x;
      else if (lastCommand.equals("*")) result *= x;
      else if (lastCommand.equals("/")) result /= x;
      else if (lastCommand.equals("=")) result = x;
   }  
}

  

package webstart;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.jnlp.BasicService;
import javax.jnlp.FileContents;
import javax.jnlp.FileOpenService;
import javax.jnlp.FileSaveService;
import javax.jnlp.PersistenceService;
import javax.jnlp.ServiceManager;
import javax.jnlp.UnavailableServiceException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

/**
 * 带有计算器面板和菜单的框架,用于装载和保存计算器历史记录。
 */
public class CalculatorFrame extends JFrame
{
   private CalculatorPanel panel;

   public CalculatorFrame()
   {
      setTitle();
      panel = new CalculatorPanel();
      add(panel);

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

      JMenuItem openItem = fileMenu.add("Open");
      openItem.addActionListener(event -> open());
      JMenuItem saveItem = fileMenu.add("Save");
      saveItem.addActionListener(event -> save());
      
      pack();
   }

   /**
      * 从持久存储获取标题,或者在没有优先条目的情况下向用户请求标题
    * entry.
    */
   public void setTitle()
   {
      try
      {
         String title = null;

         BasicService basic = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
         URL codeBase = basic.getCodeBase();

         PersistenceService service = (PersistenceService) ServiceManager
               .lookup("javax.jnlp.PersistenceService");
         URL key = new URL(codeBase, "title");

         try
         {
            FileContents contents = service.get(key);
            InputStream in = contents.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            title = reader.readLine();
         }
         catch (FileNotFoundException e)
         {
            title = JOptionPane.showInputDialog("Please supply a frame title:");
            if (title == null) return;

            service.create(key, 100);
            FileContents contents = service.get(key);
            OutputStream out = contents.getOutputStream(true);
            PrintStream printOut = new PrintStream(out);
            printOut.print(title);
         }
         setTitle(title);
      }
      catch (UnavailableServiceException | IOException e)
      {
         JOptionPane.showMessageDialog(this, e);
      }
   }

   /**
    * 打开历史文件并更新显示。
    */
   public void open()
   {
      try
      {
         FileOpenService service = (FileOpenService) ServiceManager
               .lookup("javax.jnlp.FileOpenService");
         FileContents contents = service.openFileDialog(".", new String[] { "txt" });

         JOptionPane.showMessageDialog(this, contents.getName());
         if (contents != null)
         {
            InputStream in = contents.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = reader.readLine()) != null)
            {
               panel.append(line);
               panel.append("
");
            }
         }
      }
      catch (UnavailableServiceException e)
      {
         JOptionPane.showMessageDialog(this, e);
      }
      catch (IOException e)
      {
         JOptionPane.showMessageDialog(this, e);
      }
   }

   /**
    *    将计算器历史保存到文件中。
    */
   public void save()
   {
      try
      {
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         PrintStream printOut = new PrintStream(out);
         printOut.print(panel.getText());
         InputStream data = new ByteArrayInputStream(out.toByteArray());
         FileSaveService service = (FileSaveService) ServiceManager
               .lookup("javax.jnlp.FileSaveService");
         service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt");
      }
      catch (UnavailableServiceException e)
      {
         JOptionPane.showMessageDialog(this, e);
      }
      catch (IOException e)
      {
         JOptionPane.showMessageDialog(this, e);
      }
   }
}

  

package webstart;

import java.awt.*;
import javax.swing.*;

/**
 * 具有计算历史的计算器,可以作为Java Web Start应用程序部署。
 * @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);
         });
   }
}

  实验2GUI综合编程练习

练习1:

package ID;

import java.io.BufferedReader;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.TimerTask;
import javax.swing.*;
import java.awt.event.*;

public class Main extends JFrame {
	private static ArrayList studentlist;
	private static ArrayList<Student> list;
	private JPanel buttonPanel;

	Scanner scanner = new Scanner(System.in);

	public Main() {
		studentlist = new ArrayList<>();

		JTextArea jt = new JTextArea();
		jt.setBounds(300, 100, 800, 600);
		buttonPanel = new JPanel();

		JButton jButton = new JButton("字典排序");
		JButton jButton1 = new JButton("年龄最大和年龄最小");
		JLabel lab = new JLabel("猜猜你的老乡");
		JTextField jt1 = new JTextField();
		JLabel lab1 = new JLabel("找找同龄人(年龄相近):");
		JTextField jt2 = new JTextField();
		JLabel lab2 = new JLabel("输入你的身份证号码:");
		JTextField jt3 = new JTextField();
		JButton jButton2 = new JButton("退出");
		buttonPanel.setLayout(null);
		jButton.setBounds(0, 50, 100, 30);
		jButton1.setBounds(0, 100, 160, 30);
		lab2.setBounds(0, 200, 100, 30);
		lab.setBounds(0, 150, 150, 30);
		jt1.setBounds(150, 150, 100, 30);
		lab1.setBounds(0, 250, 150, 30);
		jt2.setBounds(100, 250, 160, 30);
		jt3.setBounds(100, 200, 160, 30);
		jButton2.setBounds(0, 300, 60, 30);
		buttonPanel.add(jButton);
		buttonPanel.add(jButton1);
		buttonPanel.add(lab);
		buttonPanel.add(jt1);
		buttonPanel.add(lab1);
		buttonPanel.add(jt2);
		buttonPanel.add(lab2);
		buttonPanel.add(jt3);
		buttonPanel.add(jButton2);
		add(buttonPanel);
		buttonPanel.add(jt);
		
		try {
			BufferedReader in = new BufferedReader(new FileReader("身份证号.txt"));
			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();
		}
		jButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				jt.setText(null);
				Collections.sort(studentlist);
				jt.setText(studentlist.toString());
				// jt.append(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 = ((Student) studentlist.get(i)).getage();
					if (j > max) {
						max = j;
						k1 = i;
					}
					if (j < min) {
						min = j;
						k2 = i;
					}

				}
				jt.setText("年龄最大:" + studentlist.get(k1) + "年龄最小:" + studentlist.get(k2));
			}
		});
		jButton2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
				System.exit(0);
			}
		});
		jt1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String find = jt1.getText();
				String text = "";
				String place = find.substring(0, 3);
				for (int i = 0; i < studentlist.size(); i++) {
					if (((Student) studentlist.get(i)).getprovince().substring(1, 4).equals(place)) {
						text += "
" + studentlist.get(i);
						jt.setText("老乡:" + text);
					}
				}
			}
		});
		jt2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String yourage = jt2.getText();
				int a = Integer.parseInt(yourage);
				int near = agenear(a);
				int value = a - ((Student) studentlist.get(near)).getage();
				jt.setText("年龄相近:" + studentlist.get(near));
			}
		});
		jt3.addKeyListener(new KeyAdapter() {

			public void keyTyped(KeyEvent e) {
				list = new ArrayList<>();
				Collections.sort(studentlist);
				String key = jt3.getText();
				for (int i = 1; i < studentlist.size(); i++) {
					if (((Student) studentlist.get(i)).getnumber().contains(key)) {
						list.add((Student) studentlist.get(i));
						jt.setText("你可能是:
" + list);
					}
				}
			}
		});
	}

	public static int agenear(int age) {
		int min = 53, value = 0, k = 0;
		for (int i = 0; i < studentlist.size(); i++) {
			value = ((Student) studentlist.get(i)).getage() - age;
			if (value < 0)
				value = -value;
			if (value < min) {
				min = value;
				k = i;
			}
		}
		return k;
	}
}

  

package ID;

import java.awt.*;
import javax.swing.*;
  
public class ButtonTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         JFrame frame = new Main();
         frame.setTitle("身份查询");
         frame.setBounds(50, 50, 500, 500);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

  

package ID;

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:

package 答题;

import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import javax.swing.*;
public class Exam extends JFrame {
    JPanel p=new JPanel();
    		
    JLabel timeLabel=new JLabel("开始计时:");
    JLabel time=new JLabel();//显示时间*/  
    
    JLabel[] label1=new JLabel[10];//第几题目
    JLabel[] label2=new JLabel[10];//第一个运算数
    JLabel[] label3=new JLabel[10];//+_*/ 号
    JLabel[] label4=new JLabel[10];//第二个运算数
    JLabel[] label5=new JLabel[10];// =号
    JTextField[] field=new JTextField[10];//运算结果
    JLabel[] label6=new JLabel[10]; //对、错的符号(V 、 X)
    String[] btn_name= {"重置","提交","重考"};
    JButton[] btn=new JButton[3];
    Panel2 panel2=null;
    int ExamCount=0;//已考试几次
    JLabel examLabel=new JLabel();//已考试几次的显示标签
    double[] result=new double[10];//存储计算10条题所得答案
    public static void main(String[] args) {
        new Exam("简单测试系统").setVisible(true);
    }
     
    /*public void setTime() {
        new T().start();
    }*/
    public Exam(String title) {
        setTitle(title);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(3);
        setSize(400,500);
        setResizable(false);
        setForeground(Color.blue);
        add(new Panel1(),BorderLayout.NORTH);
        panel2=new Panel2();
        add(new JScrollPane(panel2));
        add(new Panel3(),BorderLayout.WEST);       
    }
    public void startExam() {
        int num1=0;
        int num2=0;
        String[] quots= {"+","-","*","/"};
        String quot=null;
        Random ran=null;
        ran=new Random(System.currentTimeMillis());
        Box box=Box.createVerticalBox();
         
        for(int i=0;i<10;i++) {
            num1=ran.nextInt(100)+1;//排除运算数 0
            num2=ran.nextInt(100)+1;
            int n=ran.nextInt(4);
            quot=new String(quots[n]);//得到随机+-*/ 符号
            switch(quot) {
            case "+":
                result[i]=num1+num2;
                break;
            case "-":
                result[i]=num1-num2;
                break;
            case "*":
                result[i]=num1*num2;
                break;
            case "/":
                result[i]=num1/(num2*1.0);
                result[i]=Math.round(result[i]*100)/100.0;
                break;
            }
             
            label1[i]=new JLabel("第"+(i+1)+"题:");
            label2[i]=new JLabel(num1+"");
             
            label3[i]=new JLabel(quot);
            label4[i]=new JLabel(num2+"");
            label5[i]=new JLabel("=");
            field[i]=new JTextField();
            field[i].setPreferredSize(new Dimension(60,20));
            field[i].addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent ee) {
                    if((ee.getKeyChar()>‘9‘ || ee.getKeyChar()<‘0‘) && ee.getKeyChar()!=45 && ee.getKeyChar()!=‘.‘) {
                        ee.consume();
                    }
                }
            });
            label6[i]=new JLabel("");  
            Box hbox=Box.createHorizontalBox();
            hbox.add(label1[i]);        //题目
            hbox.add(Box.createHorizontalStrut(20));
            hbox.add(label2[i]);  //  1运算数
            hbox.add(Box.createHorizontalStrut(5));
            hbox.add(label3[i]);    //  +_*/号
            hbox.add(Box.createHorizontalStrut(5));
            hbox.add(label4[i]);     //  2运算数
            hbox.add(Box.createHorizontalStrut(5));
            hbox.add(label5[i]);     //  =号
            hbox.add(Box.createHorizontalStrut(5));
            hbox.add(field[i]); //所填的结果
            hbox.add(Box.createHorizontalStrut(20));
            hbox.add(label6[i]);
            box.add(hbox);
            box.add(Box.createVerticalStrut(20));
        }
        panel2.add(box);
        panel2.validate();
    }
    int submitCount=0;//提交次数
    class Listener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            JButton button=(JButton)e.getSource();
            if(button==btn[0]) {
                //setTime();
                startExam();
                ExamCount++;
                btn[0].setEnabled(false);
                examLabel.setText("现在开始考试,开始倒计时间!");
                 
                for(int i=1;i<4;i++) {
                    btn[i].setEnabled(true);
                }
            }
            if(button==btn[1]) {
                for(int i=0;i<10;i++) {
                    field[i].setText("");
                }
            }
            if(button==btn[2] ) {
                rightResultCount=0;
                btn[2].setEnabled(false);
                double yourResult=0;//每条题目所填答案
                for(int i=0;i<10;i++) {
                    try {
                        yourResult=Double.parseDouble(field[i].getText().trim());
                    }catch(Exception ee) {}
                     
                    if(yourResult==result[i]) {
                        rightResultCount++;
                        label6[i].setText("V");
                        label6[i].setForeground(Color.BLUE);
                         
                    }else {
                        label6[i].setText("X");
                        label6[i].setForeground(Color.RED);
                         
                    }
                }
                examLabel.setText("你答对了 "+rightResultCount+
                        " 道题,答错了"+(10-rightResultCount)+" 道题!"+
                        "考试得分是: "+rightResultCount*10+" 分!");
            }
            if(button==btn[3]) {
                btn[2].setEnabled(true);
                panel2.removeAll();
                startExam();
                ExamCount++;
                examLabel.setText("你已经考试第 "+ExamCount+" 次");
                btn[3].setEnabled(false);
                for(int i=0;i<10;i++) {
                    field[i].setText("");
                    label6[i].setText("");
                }
                panel2.repaint();
                panel2.validate();
            }
            if(btn[2].isEnabled()==false && btn[3].isEnabled()==false) {
                btn[1].setEnabled(false);
            }
        }
    }
     
    class Panel1 extends JPanel{
        public Panel1() {
            setPreferredSize(new Dimension(350,120));
            setLayout(new GridLayout(3,1,10,10));
            JTextArea area=new JTextArea("答案中有小数的,保留2位!");
            area.setLineWrap(true);
            area.setEditable(false);
            add(area);
            add(examLabel);
            //p.add(timeLabel);
            //p.add(time);
            add(p);
        }
    }
 
    class Panel2 extends JPanel{
        public Panel2() {
            setPreferredSize(new Dimension(400,600));  
        }
    }
     
    class Panel3 extends JPanel{
        public Panel3() {
            setPreferredSize(new Dimension(50,100));
            setBackground(Color.LIGHT_GRAY);
            for(int i=0;i<4;i++) {
                btn[i]=new JButton(btn_name[i]);
                btn[i].addActionListener(new Listener());
                add(btn[i]);
                if(i>0) {
                    btn[i].setEnabled(false);
                }
            }
        }
    }
}

  

实验总结:

1.JAR文件

     Java程序的打包:程序编译完成后,程序员 将.class文件压缩打包为.jar文件后,GUI界面 程序就可以直接双击图标运行。.jar文件(Java归档)既可以包含类文件,也可 以包含诸如图像和声音这些其它类型的文件。 JAR文件是压缩的,它使用ZIP压缩格式。

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

创建JAR文件:jar cf jar-file input-file(s)

                              c---want to Create a JAR file.

查看JAR文件:jar tf jar-file

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

提取JAR文件:jar xf jar-file [archived-file(s)]

                              x---want to extract files from the JAR archive.

更新JAR文件:jar uf jar-file input-file(s)

                              u---want to update an existing JAR file.

索引JAR文件:jar i jar-file

                               i---index an existing JAR file.

运行JAR文件:(1)用户可以通过命令来启动应用程序: java –jar MyProgram.jar

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

资源:

    Java 中,应用程序使的类通常需要一些相关数 中,应用程序使的类通常需要一些相关数 据文件,这些称为资源 (Resource) 。
–图像和声音文件。
–带有消息字符串和按钮标签的文本件。 带有消息字符串和按钮标签的文本件。 带有消息字符串和按钮标签的文本件。
–二进制数据文件,如:描述地图布局的。 二进制数据文件,如:描述地图布局的。 二进制数据文件,如:描述地图布局的。

技术分享图片

javac ResourceTest.java

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

– java –jar ResourceTest.jar




以上是关于孔维滢 20171010110《面向对象程序设计(java)》第十五周学习总结的主要内容,如果未能解决你的问题,请参考以下文章

孔维滢 20171010110《面向对象程序设计(java)》第十五周学习总结

孔维滢 20171010110《面向对象程序设计(java)》第十七周学习总结

孔维滢201771010110《面向对象程序设计(java)》第一周学习总结

201771010110孔维滢《面向对象程序设计(java)》第十三周学习总结

201771010110孔维滢《面向对象程序设计(java)》第二周学习总结

201771010110孔维滢《面向对象程序设计(java)》第十二周学习总结