201771010102 常惠琢《面向对象程序设计(Java)》第(十五)周学习总结

it2022-05-09  22

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

实验时间 2018-12-6

1、实验目的与要求

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

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

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

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

2、实验内容和步骤

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

测试程序1

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

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

l 掌握创建JAR文件的方法;

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(); frame.setTitle("ResourceTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } /** * 一个加载图像和文本资源的框架。 */ 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); URL aboutURL = getClass().getResource("about.gif"); Image img = new ImageIcon(aboutURL).getImage(); setIconImage(img); JTextArea textArea = new JTextArea(); InputStream stream = getClass().getResourceAsStream("about.txt"); try (Scanner in = new Scanner(stream, "UTF-8")) { while (in.hasNext()) textArea.append(in.nextLine() + "\n"); } add(textArea); } } View Code

 

测试程序2

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

l 了解Properties类中常用的方法;

1 package preferences; 2 3 import java.awt.*; 4 import java.io.*; 5 import java.util.prefs.*; 6 7 import javax.swing.*; 8 import javax.swing.filechooser.*; 9 10 /** 11 *测试偏好设定的程式,程序对应的画面 12 * 位置、大小和文本。 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 *从用户首选项恢复位置和大小并更新 30 * 离开时有优先考虑。 31 */ 32 class PreferencesFrame extends JFrame 33 { 34 private static final int DEFAULT_WIDTH = 300; 35 private static final int DEFAULT_HEIGHT = 200; 36 private Preferences root = Preferences.userRoot(); 37 private Preferences node = root.node("/com/horstmann/corejava"); 38 39 public PreferencesFrame() 40 { 41 // 从首选项中获取位置、大小、标题 42 43 int left = node.getInt("left", 0); 44 int top = node.getInt("top", 0); 45 int width = node.getInt("width", DEFAULT_WIDTH); 46 int height = node.getInt("height", DEFAULT_HEIGHT); 47 setBounds(left, top, width, height); 48 49 //如果未给定标题,请询问用户 50 51 String title = node.get("title", ""); 52 if (title.equals("")) 53 title = JOptionPane.showInputDialog("Please supply a frame title:"); 54 if (title == null) title = ""; 55 setTitle(title); 56 57 // 设置显示XML文件的文件选择器 58 59 final JFileChooser chooser = new JFileChooser(); 60 chooser.setCurrentDirectory(new File(".")); 61 chooser.setFileFilter(new FileNameExtensionFilter("XML files", "xml")); 62 63 // 设置菜单 64 65 JMenuBar menuBar = new JMenuBar(); 66 setJMenuBar(menuBar); 67 JMenu menu = new JMenu("File"); 68 menuBar.add(menu); 69 70 JMenuItem exportItem = new JMenuItem("Export preferences"); 71 menu.add(exportItem); 72 exportItem 73 .addActionListener(event -> { 74 if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) 75 { 76 try 77 { 78 savePreferences(); 79 OutputStream out = new FileOutputStream(chooser 80 .getSelectedFile()); 81 node.exportSubtree(out); 82 out.close(); 83 } 84 catch (Exception e) 85 { 86 e.printStackTrace(); 87 } 88 } 89 }); 90 91 JMenuItem importItem = new JMenuItem("Import preferences"); 92 menu.add(importItem); 93 importItem 94 .addActionListener(event -> { 95 if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) 96 { 97 try 98 { 99 InputStream in = new FileInputStream(chooser 100 .getSelectedFile()); 101 Preferences.importPreferences(in); 102 in.close(); 103 } 104 catch (Exception e) 105 { 106 e.printStackTrace(); 107 } 108 } 109 }); 110 111 JMenuItem exitItem = new JMenuItem("Exit"); 112 menu.add(exitItem); 113 exitItem.addActionListener(event -> { 114 savePreferences(); 115 System.exit(0); 116 }); 117 } 118 119 public void savePreferences() 120 { 121 node.putInt("left", getX()); 122 node.putInt("top", getY()); 123 node.putInt("width", getWidth()); 124 node.putInt("height", getHeight()); 125 node.put("title", getTitle()); 126 } 127 } View Code

 

 测试程序3

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

l 了解Preferences类中常用的方法;

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

测试程序4 

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

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

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

实验2GUI综合编程练习

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

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

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

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

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

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

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

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

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

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 } View Code 1 package AA; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.InputStreamReader; 7 import java.io.FileNotFoundException; 8 import java.io.IOException; 9 import java.util.ArrayList; 10 import java.util.Arrays; 11 import java.util.Collections; 12 import java.util.Scanner; 13 import java.awt.*; 14 import javax.swing.*; 15 import java.awt.event.*; 16 17 public class Main extends JFrame { 18 private static ArrayList<Student> studentlist; 19 private static ArrayList<Student> list; 20 private JPanel panel; 21 private JPanel buttonPanel; 22 private static final int DEFAULT_WITH = 900; 23 private static final int DEFAULT_HEIGHT = 600; 24 25 public Main() { 26 studentlist = new ArrayList<>(); 27 Scanner scanner = new Scanner(System.in); 28 File file = new File("G:\\身份证号.txt"); 29 try { 30 FileInputStream fis = new FileInputStream(file); 31 BufferedReader in = new BufferedReader(new InputStreamReader(fis)); 32 String temp = null; 33 while ((temp = in.readLine()) != null) { 34 35 Scanner linescanner = new Scanner(temp); 36 37 linescanner.useDelimiter(" "); 38 String name = linescanner.next(); 39 String number = linescanner.next(); 40 String sex = linescanner.next(); 41 String age = linescanner.next(); 42 String province = linescanner.nextLine(); 43 Student student = new Student(); 44 student.setName(name); 45 student.setnumber(number); 46 student.setsex(sex); 47 int a = Integer.parseInt(age); 48 student.setage(a); 49 student.setprovince(province); 50 studentlist.add(student); 51 52 } 53 } catch (FileNotFoundException e) { 54 System.out.println("文件找不到"); 55 e.printStackTrace(); 56 } catch (IOException e) { 57 System.out.println("文件读取错误"); 58 e.printStackTrace(); 59 } 60 panel = new JPanel(); 61 panel.setLayout(new BorderLayout()); 62 JTextArea A = new JTextArea(); 63 panel.add(A); 64 add(panel, BorderLayout.NORTH); 65 buttonPanel = new JPanel(); 66 67 buttonPanel.setLayout(new GridLayout(6, 2)); 68 JButton jButton = new JButton("字典排序"); 69 JButton jButton1 = new JButton("年龄最大和年龄最小"); 70 JLabel lab1 = new JLabel("寻找你的老乡"); 71 JTextField a1 = new JTextField(); 72 JLabel lab2 = new JLabel("寻找找同龄人:"); 73 JTextField a2 = new JTextField(); 74 JLabel lab3 = new JLabel("输入身份证号码查询信息:"); 75 JTextField a3 = new JTextField(); 76 JButton jButton2 = new JButton("退出"); 77 78 jButton.addActionListener(new ActionListener() { 79 public void actionPerformed(ActionEvent e) { 80 Collections.sort(studentlist); 81 A.setText(studentlist.toString()); 82 } 83 }); 84 jButton1.addActionListener(new ActionListener() { 85 public void actionPerformed(ActionEvent e) { 86 int max = 0, min = 100; 87 int j, k1 = 0, k2 = 0; 88 for (int i = 1; i < studentlist.size(); i++) { 89 j = studentlist.get(i).getage(); 90 if (j > max) { 91 max = j; 92 k1 = i; 93 } 94 if (j < min) { 95 min = j; 96 k2 = i; 97 } 98 99 } 100 A.setText("年龄最大:" + studentlist.get(k1) + "年龄最小:" + studentlist.get(k2)); 101 } 102 }); 103 jButton2.addActionListener(new ActionListener() { 104 public void actionPerformed(ActionEvent e) { 105 dispose(); 106 System.exit(0); 107 } 108 }); 109 a1.addActionListener(new ActionListener() { 110 public void actionPerformed(ActionEvent e) { 111 String find = a1.getText(); 112 String text=""; 113 String place = find.substring(0, 3); 114 for (int i = 0; i < studentlist.size(); i++) { 115 if (studentlist.get(i).getprovince().substring(1, 4).equals(place)) { 116 text+="\n"+studentlist.get(i); 117 A.setText("老乡:" + text); 118 } 119 } 120 } 121 }); 122 a2.addActionListener(new ActionListener() { 123 public void actionPerformed(ActionEvent e) { 124 String yourage = a2.getText(); 125 int a = Integer.parseInt(yourage); 126 int near = agenear(a); 127 int value = a - studentlist.get(near).getage(); 128 A.setText("年龄相近:" + studentlist.get(near)); 129 } 130 }); 131 a3.addActionListener(new ActionListener() { 132 public void actionPerformed(ActionEvent e) { 133 list = new ArrayList<>(); 134 Collections.sort(studentlist); 135 String key = a3.getText(); 136 for (int i = 1; i < studentlist.size(); i++) { 137 if (studentlist.get(i).getnumber().contains(key)) { 138 list.add(studentlist.get(i)); 139 A.setText("结果:\n" + list); 140 141 } 142 } 143 } 144 }); 145 buttonPanel.add(jButton); 146 buttonPanel.add(jButton1); 147 buttonPanel.add(lab1); 148 buttonPanel.add(a1); 149 buttonPanel.add(lab2); 150 buttonPanel.add(a2); 151 buttonPanel.add(lab3); 152 buttonPanel.add(a3); 153 buttonPanel.add(jButton2); 154 add(buttonPanel, BorderLayout.SOUTH); 155 setSize(DEFAULT_WITH, DEFAULT_HEIGHT); 156 } 157 158 public static int agenear(int age) { 159 int min = 53, value = 0, k = 0; 160 for (int i = 0; i < studentlist.size(); i++) { 161 value = studentlist.get(i).getage() - age; 162 if (value < 0) 163 value = -value; 164 if (value < min) { 165 min = value; 166 k = i; 167 } 168 } 169 return k; 170 } 171 172 } View Code 1 private String name; 2 private String number ; 3 private String sex ; 4 private int age; 5 private String province; 6 7 public String getName() { 8 return name; 9 } 10 public void setName(String name) { 11 this.name = name; 12 } 13 public String getnumber() { 14 return number; 15 } 16 public void setnumber(String number) { 17 this.number = number; 18 } 19 public String getsex() { 20 return sex ; 21 } 22 public void setsex(String sex ) { 23 this.sex =sex ; 24 } 25 public int getage() { 26 27 return age; 28 } 29 public void setage(int age) { 30 31 this.age= age; 32 } 33 34 public String getprovince() { 35 return province; 36 } 37 public void setprovince(String province) { 38 this.province=province ; 39 } 40 41 public int compareTo(Student o) { 42 return this.name.compareTo(o.getName()); 43 } 44 45 public String toString() { 46 return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n"; 47 } 48 } View Code

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

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

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

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

1 package A; 2 3 import java.io.FileNotFoundException; 4 import java.io.IOException; 5 import java.io.PrintWriter; 6 import java.util.Scanner; 7 public class Main { 8 9 public static void main(String[] args) { 10 Scanner in = new Scanner(System.in); 11 counter min=new counter(); 12 PrintWriter out = null; 13 try { 14 out = new PrintWriter("result.txt"); 15 int sum = 0; 16 for (int i = 1; i <=10; i++) { 17 int a = (int) Math.round(Math.random() * 100); 18 int b = (int) Math.round(Math.random() * 100); 19 int menu = (int) Math.round(Math.random() * 3); 20 switch (menu) { 21 case 0: 22 System.out.println(i+":"+a + "+" + b + "="); 23 int c1 = in.nextInt(); 24 out.println(a + "+" + b + "=" + c1); 25 if (c1 == (a + b)) { 26 sum += 10; 27 System.out.println("恭喜答案正确"); 28 } else { 29 System.out.println("抱歉,答案错误"); 30 } 31 break; 32 case 1: 33 while (a < b) { 34 b = (int) Math.round(Math.random() * 100); 35 } 36 System.out.println(i+":"+a + "-" + b + "="); 37 int c2 = in.nextInt(); 38 out.println(a + "-" + b + "=" + c2); 39 if (c2 == (a - b)) { 40 sum += 10; 41 System.out.println("恭喜答案正确"); 42 } else { 43 System.out.println("抱歉,答案错误"); 44 } 45 46 break; 47 case 2: 48 System.out.println(i+":"+a + "*" + b + "="); 49 int c3 = in.nextInt(); 50 out.println(a + "*" + b + "=" + c3); 51 if (c3 == a * b) { 52 sum += 10; 53 System.out.println("恭喜答案正确"); 54 } else { 55 System.out.println("抱歉,答案错误"); 56 } 57 58 break; 59 case 3: 60 while(b == 0){ 61 b = (int) Math.round(Math.random() * 100); 62 } 63 while(a % b != 0){ 64 a = (int) Math.round(Math.random() * 100); 65 66 } 67 System.out.println(i+":"+a + "/" + b + "="); 68 int c4 = in.nextInt(); 69 if (c4 == a / b) { 70 sum += 10; 71 System.out.println("恭喜,答案正确"); 72 } else { 73 System.out.println("抱歉,答案错误"); 74 } 75 76 break; 77 } 78 } 79 System.out.println("你的得分为" + sum); 80 out.println("你的得分为" + sum); 81 out.close(); 82 } catch (FileNotFoundException e) { 83 e.printStackTrace(); 84 } 85 } 86 } View Code 1 package A; 2 3 public class counter<T> { 4 private T a; 5 private T b; 6 public counter() { 7 a=null; 8 b=null; 9 } 10 public counter(T a,T b) { 11 this.a=a; 12 this.b=b; 13 } 14 public int count1(int a,int b) { 15 return a+b; 16 } 17 public int count2(int a,int b) { 18 return a-b; 19 } 20 public int count3(int a,int b) { 21 return a*b; 22 } 23 public int count4(int a,int b) { 24 return a/b; 25 } 26 } 27 28 counter View Code

实验总结:

清单文件

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

转载于:https://www.cnblogs.com/hongyanohongyan/p/10078431.html


最新回复(0)