孔維瀅 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() + "\n"); } 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("\n" + result); lastCommand = command; display.append("\n"); 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("\n"); } } } 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); }); } }
實驗2:GUI綜合編程練習
練習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 += "\n" + 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("你可能是:\n" + 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+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n"; } }
練習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)》第十五周學習總結