第一篇:java程序設計簡明教程--上機練習題參考答案
《java程序設計簡明教程》上機練習題參考答案
目 錄
上機練習題1..................................................3 1.用循環(huán)語句分別打印九九乘法表......................................................................................................................3 2.定義兩個數組......................................................................................................................................................4 3.編寫一個簡單的考試程序..................................................................................................................................4 上機練習題2..................................................6 1.編寫程序,包括一個文本域和三個命令按鈕...................................................................................................6 2.編寫程序,包括一個文本框、一個密碼框和兩個按鈕...................................................................................7 3.編寫程序,建立一個帶有菜單的窗體..............................................................................................................8 4.編寫程序,將窗口尺寸設置為不可更改,并處理窗口事件...........................................................................9 5.編寫程序,用列表框列出一些選項,設置一個按鈕.....................................................................................10 6.編寫程序,用標簽顯示一道簡單測試題,答案使用單選按鈕列出.............................................................11 上機練習題3.................................................13 1.編寫Application在窗口內畫54個不同顏色的小圓......................................................................................13 2.編制Applet程序,使用Graphics類中的各種圖形繪制方法........................................................................14 3.編制Applet程序,以百葉窗效果顯示圖像....................................................................................................14 4.編制Applet程序,實現(xiàn)12個鋼琴鍵及其聲音的模擬..................................................................................17 上機練習題4.................................................18 1.假設在addressbook數據庫表中,存在多個姓氏相同的人,根據這一情況,建立相應的查詢功能.......18 2.編寫一個應用程序,使其可以從一個數據庫的某個表中查詢一個列的所有信息.....................................20 3.設計一個數據庫應用程序,功能是在學生數據庫的成績表中加入某門課程的所有學生的成績.............23 上機練習題5.................................................26 1.編寫GUI程序,制作一個文本文件閱讀器....................................................................................................26
Java程序設計簡明教程
2.編制程序,計算表達式“2*4*6+8*10*12+……+26*28*30”的值,并把結果輸出到文件中....................27 3.編制程序............................................................................................................................................................28 4.編寫程序,實現(xiàn)壓縮、解壓縮Zip文件.........................................................................................................29 5.編寫程序,從試題文件中抽取Java單選題進行測試練習............................................................................32 上機練習題6.................................................34 1.編制程序,求如下表達式的值........................................................................................................................34 2.用繼承Thread類的方法實現(xiàn)一個多線程程序...............................................................................................35 3.編制程序,同時顯示兩個時區(qū)的時鐘,并將時鐘的結果顯示在Fram窗體中...........................................37 4.使用異常處理機制和輸入/輸出處理機制編寫一個程序................................................................................41 上機練習題7.................................................42 1.編制Applet程序,使用Graphics類的常用方法,繪制一面五星紅旗........................................................42 2.編制Applet程序,實現(xiàn)一行文字的動畫顯示,即文字跑馬燈....................................................................42 3.編制Applet程序,實現(xiàn)圖片的水中倒影........................................................................................................44 4.結合圖形用戶界面與事件處理,創(chuàng)建一個日歷GUI程序............................................................................46 上機練習題8.................................................48 1.設計Java Applet程序,實現(xiàn)在圖片上飄雪花的特效....................................................................................48 2.設計一個通訊錄,保存讀者信息....................................................................................................................50 3.構造一個程序,它在一個窗口描繪出一個小鳥的圖標.................................................................................54
上機練習題參考答案
上機練習題1 1.用循環(huán)語句分別打印如圖1-24所示的九九乘法表。【參考程序】
//文件XiTi1_1_1_1.java package XiTi;import java.io.*;import java.lang.*;public class XiTi1_1_1{ public static void main(String args[]){ String str=“ ”;int i,j;for(i=1;i<=9;i++){ for(j=1;j<=9;j++){ str=i+“*”+j+“=”+i*j;if(i
//文件XiTi1_1_3.java package XiTi;import java.io.*;import java.lang.*;public class XiTi1_1_3{ public static void main(String args[]){ String str=” “;3
Java程序設計簡明教程
int i,j;for(i=1;i<=9;i++){ for(j=1;j<=9;j++){ str=i+”*“+j+”=“+i*j;System.out.print(str.length()==5?str+” “:str+” “);} System.out.println(”“);} } } 2.定義兩個數組,首先將第一個數組中的元素復制到第二個數組中,然后將第二個數數組進行從大到小的排序,最后將兩個數組中的對應元素進行比較,試統(tǒng)計兩個數組中對應位置上相同元素的個數。
【參考程序】
//文件XiTi1_2.java package XiTi;import java.io.*;import java.lang.*;public class XiTi1_2{ public static void main(String[] args){ int a[]={278,109,063,930,589,184,505,269,8,83};int b[]=new int[10];int t,cnt=0;for(int i=0;i<10;i++)b[i]=a[i];for(int i=1;i<10;i++)for(int j=0;j<10-i;j++)if(b[j]
System.out.println(”“);System.out.println(”********************* b **********************“);System.out.println(”“);for(int i=0;i<10;i++)System.out.print(b[i]+” “);System.out.println(”“);System.out.println(”“);System.out.println(”對應元素相同的個數為:“+cnt);System.out.println(”“);} } 3.編寫一個簡單的考試程序?!緟⒖汲绦颉?/p>
上機練習題參考答案
//文件XiTi1_3.java package XiTi;import java.io.*;import java.util.Date;public class XiTi1_3{ public static void main(String[] args){ String yes=”Y“,ok=”“;int x,x1,y,opr=2,s,h,m,t1,t2;String op,str=”“,re=”“,a=”A“;do{ x=new Long(Math.round(Math.random()*99+1)).intValue();y=new Long(Math.round(Math.random()*99+1)).intValue();opr=new Long(Math.round(Math.random()*3+1)).intValue();s=new Date().getSeconds();h=new Date().getHours();m=new Date().getMinutes();t1=h*3600+m*60+s;switch(opr){ case 1: str=x+”+“+y+”=?“;re=Integer.toString(x+y);break;case 2: str=x+”-“+y+”=?“;re=Integer.toString(x-y);break;case 3: str=x+”*“+y+”=?“;re=Integer.toString(x*y);break;case 4: x1=Math.max(x,y);y=Math.min(x,y);x=x1;x=x-x%y;str=x+”/“+y+”=?“;re=Integer.toString(x/y);break;} System.out.print(str);try{ BufferedReader in =new BufferedReader(new InputStreamReader(System.in));ok=in.readLine();
}catch(IOException e){};s=new Date().getSeconds();h=new Date().getHours();m=new Date().getMinutes();t2=h*3600+m*60+s;if(ok.equals(re.trim()))System.out.println(”正確!用時:“+(t2-t1)+”秒“);else if(a.equals(ok.toUpperCase()))5
Java程序設計簡明教程
System.out.println(”答案:“+re+”,請多努力!“);else System.out.println(”錯誤!答案:“+re);System.out.print(”繼續(xù)嗎(Y/N)?“);try{ BufferedReader in =new BufferedReader(new InputStreamReader(System.in));ok=in.readLine();
}catch(IOException e){};}while(yes.equals(ok.toUpperCase()));System.out.println(”“);} }
上機練習題2 1.編寫程序,包括一個文本域和三個命令按鈕,按鈕標題分別為紅色、黃色和藍色,單擊相應的按鈕,將文本域的前景色設置為紅色、黃色和藍色。
【參考程序】
import javax.swing.*;import javax.swing.event.*;import java.awt.event.*;import java.awt.*;public class xiti2_1 extends JFrame implements ActionListener{ JButton red,yellow,blue;JTextArea ta=new JTextArea(5,20);xiti2_1(){ red=new JButton(”紅色“);yellow=new JButton(”黃色“);blue=new JButton(”藍色“);red.addActionListener(this);yellow.addActionListener(this);blue.addActionListener(this);JPanel jp=new JPanel();jp.setLayout(new FlowLayout(FlowLayout.CENTER));jp.add(red);jp.add(yellow);jp.add(blue);Container con=getContentPane();con.add(ta,BorderLayout.CENTER);con.add(jp,BorderLayout.SOUTH);setSize(300,200);setTitle(”上機練習題2_1“);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);validate();} public void actionPerformed(ActionEvent e){ JButton btn=(JButton)e.getSource();if(btn==red){ ta.setForeground(Color.red);
上機練習題參考答案
} if(btn==yellow){ ta.setForeground(Color.yellow);} if(btn==blue){ ta.setForeground(Color.blue);} } public static void main(String args[]){ new xiti2_1();} } 2.編寫程序,包括一個文本框、一個密碼框和兩個按鈕。按鈕標題分別為確定和取消,用戶在密碼框中輸入密碼,單擊確定按鈕,將在密碼框中輸入的字符顯示在文本框中。
【參考程序】
import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;public class xiti2_2 extends JFrame implements ActionListener{ JPanel p1=new JPanel();JPanel p2=new JPanel();JPanel p3=new JPanel();JPanel p4=new JPanel();JPanel p5=new JPanel();JTextField text=new JTextField(15);JPasswordField password=new JPasswordField(15);JButton ok=new JButton(”確定“);JButton cancel=new JButton(”取消“);xiti2_2(){ Container con=getContentPane();con.setLayout(new GridLayout(5,1));p2.add(new JLabel(”密碼:“));p2.add(password);p3.add(new JLabel(”文本:“));p3.add(text);p4.add(ok);p4.add(cancel);ok.addActionListener(this);cancel.addActionListener(this);con.add(p1);con.add(p2);con.add(p3);con.add(p4);con.add(p5);setSize(300,200);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setTitle(”上機練習題2_2“);validate();} public void actionPerformed(ActionEvent e){ if(e.getSource()==ok){ text.setText(password.getText());7
Java程序設計簡明教程
} if(e.getSource()==cancel){ dispose();System.exit(0);} } public static void main(String args[]){ new xiti2_2();} } 3.編寫程序,建立一個帶有菜單的窗體。當用戶選擇“Color”或“Style”菜單的相關選項時,標簽中文字的字體和顏色會發(fā)生相應的變化。
【參考程序】
import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;class xiti2_3 extends JFrame implements ActionListener{ JMenuBar menubar=new JMenuBar();JTextArea ta=new JTextArea(”Hello Java!“);xiti2_3(){ setJMenuBar(menubar);JMenu menu,submenu;JMenuItem menuItem;menu=new JMenu(”Color“);menu.setMnemonic(KeyEvent.VK_C);menubar.add(menu);menuItem=new JMenuItem(”Yellow“);menuItem.setMnemonic(KeyEvent.VK_Y);menuItem.addActionListener(this);menu.add(menuItem);menuItem=new JMenuItem(”O(jiān)range“);menuItem.setMnemonic(KeyEvent.VK_O);menuItem.addActionListener(this);menu.add(menuItem);menuItem=new JMenuItem(”Pink“,KeyEvent.VK_P);menuItem.addActionListener(this);menu.add(menuItem);menuItem=new JMenuItem(”Blue“);menuItem.setMnemonic(KeyEvent.VK_B);menuItem.addActionListener(this);menu.add(menuItem);menu=new JMenu(”Style“);menu.setMnemonic(KeyEvent.VK_S);menubar.add(menu);menuItem=new JMenuItem(”Plain“);menuItem.setMnemonic(KeyEvent.VK_P);menuItem.addActionListener(this);menu.add(menuItem);menuItem=new JMenuItem(”Bold“);menuItem.setMnemonic(KeyEvent.VK_B);menuItem.addActionListener(this);8
上機練習題參考答案
menu.add(menuItem);menuItem=new JMenuItem(”Italic“);menuItem.setMnemonic(KeyEvent.VK_I);menuItem.addActionListener(this);menu.add(menuItem);menu=new JMenu(”Exit“);menu.setMnemonic(KeyEvent.VK_E);menubar.add(menu);menuItem=new JMenuItem(”Close Window“);menuItem.setMnemonic(KeyEvent.VK_W);menuItem.addActionListener(this);menu.add(menuItem);Container cp=getContentPane();cp.add(ta,BorderLayout.SOUTH);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setTitle(”菜單演示“);setSize(300,200);setVisible(true);} public void actionPerformed(ActionEvent e){ if(e.getActionCommand()==”Yellow“)ta.setForeground(Color.yellow);if(e.getActionCommand()==”O(jiān)range“)ta.setForeground(Color.orange);if(e.getActionCommand()==”Pink“)ta.setForeground(Color.pink);if(e.getActionCommand()==”Blue“)ta.setForeground(Color.blue);if(e.getActionCommand()==”Plain“)ta.setFont(new Font(”Dialog“,Font.PLAIN,24));if(e.getActionCommand()==”Bold“)ta.setFont(new Font(”Dialog“,Font.BOLD,24));if(e.getActionCommand()==”Italic“)ta.setFont(new Font(”Dialog“,Font.ITALIC,24));if(e.getActionCommand()==”Close Window“)System.exit(0);} public static void main(String args[]){ xiti2_3 menuexmple=new xiti2_3();} } 4.編寫程序,將窗口尺寸設置為不可更改,并處理窗口事件,使得點擊窗口關閉按鈕時,會彈出對話框,提示用戶是否確定要關閉窗口。
【參考程序】
import java.awt.event.*;import javax.swing.*;class MyFrame extends JFrame{ private JLabel label;public MyFrame(){ setTitle(”我的窗口“);label=new JLabel(”請點擊關閉按鈕!“,JLabel.CENTER);getContentPane().add(label);9
Java程序設計簡明教程
//為窗口添加關閉事件
addWindowListener(new WindowCloseListener(this));//將點擊窗口關閉按鈕默認的關閉窗口功能去掉
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//設置窗口大小不可更改 setResizable(false);setSize(300,200);setVisible(true);} class WindowCloseListener extends WindowAdapter{ JFrame f;public WindowCloseListener(JFrame frame){ f=frame;//f是對話框的父窗口 } public void windowClosing(WindowEvent e){ int i=JOptionPane.showConfirmDialog(f,”確定要關“,”“,JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);if(i==JOptionPane.OK_OPTION){ System.exit(0);//點擊確定退出程序 } } } public static void main(String[] args){ JFrame frame=new MyFrame();} }
閉窗口嗎?5.編寫程序,用列表框列出一些選項,設置一個按鈕,點擊按鈕就會將所選的選項添加到另一個列表框中,其中第二個列表框中顯示的已選項目可以刪除。程序運行界面如圖2-16所示。
【參考程序】
import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;class MyList extends JFrame { JPanel panel;JButton add,remove;DefaultListModel listModel1,listModel2;JList list1,list2;String[] s={”計算機科學與技術“,”計算機通信“,”應用電子“,”電子商務“,”會計電算化“,”法律“,”工商管理“,”生物技術“,”建筑工程技術“,”工業(yè)設計“,”商務英語“,”統(tǒng)計“};ArrayList array1,array2;public MyList(){ setTitle(”列表框“);add=new JButton(”>>“);add.addActionListener(new AddActionListener());//為按鈕注冊監(jiān)聽器 remove=new JButton(”<<“);remove.addActionListener(new RemoveActionListener());//為按鈕注冊監(jiān)聽器
listModel1=new DefaultListModel();//為列表1創(chuàng)建一個列表框模型 listModel2=new DefaultListModel();//為列表2創(chuàng)建一個列表框模型 for(int i=0;i 上機練習題參考答案 list1=new JList(listModel1);//通過列表框模型1創(chuàng)建列表框1 list2=new JList(listModel2);//通過列表框模型2創(chuàng)建列表框2 panel=new JPanel();panel.setLayout(new GridLayout(2,1));//面板用來放置按鈕 panel.add(add);panel.add(remove);Container c=getContentPane();c.setLayout(new FlowLayout(FlowLayout.LEFT));c.add(list1);c.add(panel);c.add(list2);setSize(280,280);setVisible(true);} class AddActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ int id=-1;id=list1.getSelectedIndex();//得到列表框1中被選中的項 if(id>=0){ listModel2.addElement(listModel1.get(id));//向列表框2中添加所選項 listModel1.remove(id);//將列表框1中所選項刪除 } } } class RemoveActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ int id=-1;id=list2.getSelectedIndex();//得到列表框2中被選中的項 if(id>=0){ listModel1.addElement(listModel2.get(id));//向列表框1中添加所選項 listModel2.remove(id);//將列表框2中所選項刪除 } } } public static void main(String args[]){ new MyList();} } 6.編寫程序,用標簽顯示一道簡單測試題,答案使用單選按鈕列出,用戶選擇答案后,會彈出對話框顯示結果或說明。 【參考程序】 import javax.swing.*;import java.awt.*;import java.awt.event.*;class Question{ public JFrame frame;public JPanel panel;static JLabel label;public JRadioButton b1,b2,b3;static String question=”如果你意外地拿到一千元獎金,想去買一件很需要的大衣,但是錢不夠;如果去買一雙不急需要的運動鞋,則又多了數百元,你會怎么做?“;static String xx1=”自已添些錢把大衣買回來?!?11 Java程序設計簡明教程 static String xx2=”買運動鞋再去買些其它的小東西?!?static String xx3=”什么都不買先存起來?!?static String dd1=”你的決斷力不錯,雖然有時也會三心二意、猶豫徘徊,可總是在重要關頭作出決定,你最大的特色是作了決定不再反悔?!?static String dd2=”你是拿不定主意的人,做事沒主見,處處要求別人給你意見,很少自已做判斷,因為個性上你有些自卑,不肯定自己?!?static String dd3=”你是判斷力超級強的人,不客氣地說,你甚至有點莽撞,就是因為你沖動率直的個性,反而考慮不夠周詳,你常常后悔自己匆匆作決定,忽略了其它事情?!?public JOptionPane optionPane;public Question(){ //構造方法,完成布局 frame=new JFrame(”心理測試“);panel=new JPanel();panel.setLayout(new GridLayout(3,1));label=new JLabel(question,JLabel.CENTER);b1=new JRadioButton(xx1);b2=new JRadioButton(xx2);b3=new JRadioButton(xx3);ButtonGroup group=new ButtonGroup();group.add(b1);group.add(b2);group.add(b3);RadioListener myListener=new RadioListener();b1.addActionListener(myListener);b2.addActionListener(myListener);b3.addActionListener(myListener);Container c=frame.getContentPane();c.add(label,BorderLayout.NORTH);c.add(panel,BorderLayout.CENTER);panel.add(b1);panel.add(b2);panel.add(b3);frame.pack();frame.setVisible(true);} class RadioListener implements ActionListener{ public void actionPerformed(ActionEvent e){ //事件處理,點擊選項彈出相應的對話框 JRadioButton rb=(JRadioButton)e.getSource();if(rb==b1){ JOptionPane.showMessageDialog(frame,dd1,”“,JOptionPane.DEFAULT_OPTION);} if(rb==b2){ JOptionPane.showMessageDialog(frame,dd2,”“,JOptionPane.DEFAULT_OPTION);} if(rb==b3){ JOptionPane.showMessageDialog(frame,dd3,”“,JOptionPane.DEFAULT_OPTION);} } } public static void main(String[] args){ new Question();} } 12 上機練習題參考答案 上機練習題3 1.編寫Application在窗口內畫54個不同顏色的小圓,每當窗口顯示在顯示器上、從隱藏變成顯示、從縮小圖標還原、改變窗口的大小時,小圓所呈現(xiàn)的顏色也可以發(fā)生變化。(提示:使用隨機數產生隨機顏色)。程序以不同顏色的小圓鋪滿窗口。如果在窗口內只顯示某個特定的部分,其他部分則不顯示時。 【參考程序】 //文件RandomColorDemo.java import java.awt.*;import javax.swing.*;class RandomColorDemo extends JFrame{ static RandomColorDemo frm=new RandomColorDemo();public static void main(String args[]){ frm.setTitle(”Random Color“);frm.setSize(200,150);frm.setVisible(true);} public void paint(Graphics g){ for(int x=10;x<=180;x=x+20)for(int y=30;y<=140;y=y+20){ int red=(int)(Math.random()*255);// 紅色的隨機數 int green=(int)(Math.random()*255);// 綠色的隨機數 int blue=(int)(Math.random()*255);// 藍色的隨機數 g.setColor(new Color(red,green,blue));// 設置顏色 g.fillOval(x,y,15,15);// 用指定的顏色填滿小圓 } } } //文件RandomColor.java import java.awt.*;import javax.swing.*;class RandomColor extends JFrame{ static RandomColor frm=new RandomColor();public static void main(String args[]){ frm.setTitle(”Random Color“);frm.setSize(200,150);frm.setVisible(true);} public void paint(Graphics g){ g.setClip(35,37,125,100);//g.clipRect(35,37,125,100);for(int x=10;x<=180;x=x+20)for(int y=30;y<=140;y=y+20){ int red=(int)(Math.random()*255);// 紅色的隨機數 int green=(int)(Math.random()*255);// 綠色的隨機數 int blue=(int)(Math.random()*255);// 藍色的隨機數 g.setColor(new Color(red,green,blue));// 設置顏色 g.fillOval(x,y,15,15);// 用指定的顏色填滿小圓 } //g.clearRect(35,37,125,100); Java程序設計簡明教程 } } 2.編制Applet程序,使用Graphics類中的各種圖形繪制方法,繪制一個可愛的熊寶寶(或其他自己愛好的小動物,例如,小豬,小兔等)。在小應用程序瀏覽器中查看程序的執(zhí)行結果。 【參考程序】 import java.applet.*;import java.awt.*;import java.awt.Graphics;public class Bear extends Applet{ public void paint(Graphics g){ g.drawOval(100,40,180,180);//face g.fillOval(120,90,40,35);//left eye g.fillOval(220,90,40,35);//right eye g.fillOval(180,140,25,25);//nose g.setColor(Color.red);g.fillArc(166,170,50,30,180,180);//mouse g.fillArc(85,25,80,80,25,223);//left ear g.fillArc(215,25,80,80,-57,213);//right ear g.drawLine(156,210,96,320);//body g.drawLine(96,320,126,410);g.drawLine(236,210,296,320);g.drawLine(296,320,256,410);g.drawLine(126,410,256,410);g.fillOval(80,240,50,50);//arm g.fillOval(260,240,50,50);g.fillOval(100,390,50,50);//leg g.fillOval(230,390,50,50);} } 3.編制Applet程序,以百葉窗效果顯示圖像?!緟⒖汲绦颉?/p> //文件Efficient.java import java.awt.*;import java.applet.*;import java.io.*;import java.awt.image.*;public class Efficient extends Applet implements Runnable{ private Image img[],showImage;private MediaTracker imageTracker;private int ImageW,ImageH,totalImage=5,currentImage,nextImage;private Thread thread;private int delay;private int totalPix,pix1[],pix2[],pix3[],pix4[],pix5[],pixA[],pixB[];public void init(){ this.setBackground(Color.black);img=new Image[totalImage];imageTracker=new MediaTracker(this);String s=new String(”“);for(int i=0;i 上機練習題參考答案 imageTracker.addImage(img[i],0);} try{ imageTracker.waitForID(0);}catch(InterruptedException e){} if(getParameter(”delay“)==null){ delay=3000;} else{ delay=Integer.parseInt(getParameter(”delay“));} ImageW=img[0].getWidth(this);ImageH=img[0].getHeight(this);totalPix=ImageW*ImageH;pix1=new int[totalPix];PixelGrabber PG1=new PixelGrabber(img[0],0,0,ImageW,ImageH,pix1,0,ImageW);try{ PG1.grabPixels();}catch(InterruptedException ex){} pix2=new int[totalPix];PixelGrabber PG2=new PixelGrabber(img[1],0,0,ImageW,ImageH,pix2,0,ImageW);try{ PG2.grabPixels();}catch(InterruptedException ex){} pix3=new int[totalPix];PixelGrabber PG3=new PixelGrabber(img[2],0,0,ImageW,ImageH,pix3,0,ImageW);try{ PG3.grabPixels();}catch(InterruptedException ex){} pix4=new int[totalPix];PixelGrabber PG4=new PixelGrabber(img[3],0,0,ImageW,ImageH,pix4,0,ImageW);try{ PG4.grabPixels();}catch(InterruptedException ex){} pix5=new int[totalPix];PixelGrabber PG5=new PixelGrabber(img[4],0,0,ImageW,ImageH,pix5,0,ImageW);try{ PG5.grabPixels();}catch(InterruptedException ex){} currentImage=0;pixA=new int[totalPix];pixB=new int[totalPix];showImage=img[0];thread=new Thread(this);thread.start();} public void paint(Graphics g){ g.drawImage(showImage,0,0,this);} public void update(Graphics g){ paint(g);} public void run(){ 15 Java程序設計簡明教程 if(thread==null){ thread=new Thread(this);thread.start();} while(true){ try{ thread.sleep(delay);nextImage=((currentImage+1)%totalImage);if(currentImage==0){ System.arraycopy(pix1,0,pixA,0,totalPix);System.arraycopy(pix2,0,pixB,0,totalPix);showImage=createImage(new MemoryImageSource(ImageW,ImageH,pixA,0,ImageW));repaint();} if(currentImage==1){ System.arraycopy(pix2,0,pixA,0,totalPix);System.arraycopy(pix3,0,pixB,0,totalPix);showImage=createImage(new MemoryImageSource(ImageW,ImageH,pixA,0,ImageW));repaint();} if(currentImage==2){ System.arraycopy(pix3,0,pixA,0,totalPix);System.arraycopy(pix4,0,pixB,0,totalPix);showImage=createImage(new MemoryImageSource(ImageW,ImageH,pixA,0,ImageW));repaint();} if(currentImage==3){ System.arraycopy(pix4,0,pixA,0,totalPix);System.arraycopy(pix5,0,pixB,0,totalPix);showImage=createImage(new MemoryImageSource(ImageW,ImageH,pixA,0,ImageW));repaint();} if(currentImage==4){ System.arraycopy(pix5,0,pixA,0,totalPix);System.arraycopy(pix1,0,pixB,0,totalPix);showImage=createImage(new MemoryImageSource(ImageW,ImageH,pixA,0,ImageW));repaint();} while(true){ for(int i=0;i<(int)(ImageH/10);i++){ try{ thread.sleep(100);for(int j=0;j 上機練習題參考答案 currentImage=nextImage;repaint();}catch(InterruptedException e){} } } } 4.編制Applet程序,實現(xiàn)12個鋼琴鍵及其聲音的模擬?!緟⒖汲绦颉?/p> //文件Piano.java import java.awt.*;import java.applet.*;class Keyboard extends Canvas {//鋼琴鍵類 Color keyColor=Color.white;AudioClip key;int width,height;Keyboard(Color c, AudioClip k){//初始化鋼琴鍵的顏色及聲音 keyColor=c;setBackground(keyColor);key=k;width=this.getSize().width;height=this.getSize().height;} public boolean mouseDown(Event event, int x, int y){//鼠標按下事件 key.play();return true;} public void paint(Graphics g){//畫鋼琴鍵 width=this.getSize().width;height=this.getSize().height;g.setColor(Color.black);g.drawRect(0,0,width-1,height-1);} } public class Piano extends Applet{ private int height,width;private Keyboard key[];private AudioClip sound[];public void init(){ this.setLayout(null);width=this.size().width;height=this.size().height;key=new Keyboard[12];sound=new AudioClip[12];String s=new String(”“);for(int i=0;i<12;i++){ s=i + ”.au“;sound[i]=getAudioClip(getCodeBase(),s);} key[0]=new Keyboard(Color.white,sound[0]);key[1]=new Keyboard(Color.black,sound[1]);key[2]=new Keyboard(Color.white,sound[2]);key[3]=new Keyboard(Color.black,sound[3]);17 Java程序設計簡明教程 key[4]=new Keyboard(Color.white,sound[4]);key[5]=new Keyboard(Color.white,sound[5]);key[6]=new Keyboard(Color.black,sound[6]);key[7]=new Keyboard(Color.white,sound[7]);key[8]=new Keyboard(Color.black,sound[8]);key[9]=new Keyboard(Color.white,sound[9]);key[10]=new Keyboard(Color.black,sound[10]);key[11]=new Keyboard(Color.white,sound[11]);key[1].setBounds(30,0,20,60);add(key[1]);key[3].setBounds(70,0,20,60);add(key[3]);key[6].setBounds(150,0,20,60);add(key[6]);key[8].setBounds(190,0,20,60);add(key[8]);key[10].setBounds(230,0,20,60);add(key[10]);key[0].setBounds(0,0,40,110);key[2].setBounds(40,0,40,110);key[4].setBounds(80,0,40,110);key[5].setBounds(120,0,40,110);key[7].setBounds(160,0,40,110);key[9].setBounds(200,0,40,110);key[11].setBounds(240,0,40,110);add(key[0]);add(key[2]);add(key[4]);add(key[5]);add(key[7]);add(key[9]);add(key[11]);} } 上機練習題4 1.假設在addressbook數據庫表中,存在多個姓氏相同的人,根據這一情況,建立相應的查詢功能,使用戶可以在ResultSet中滾動記錄。要求設計一個合適的圖形界面。 程序源代碼如下: 【參考程序】 //數據庫連接使用ConnectServer類 import java.awt.*;import java.sql.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import java.util.*;import javax.swing.table.*;public class ex4_1 extends JFrame implements ActionListener{ JTable table;TableModel model; 上機練習題參考答案 DefaultTableModel dtm;Vector title=new Vector();JScrollPane p1;JPanel p3=new JPanel();JLabel bq1=new JLabel(”按姓氏或姓名查詢“);JTextField combSs=new JTextField(6);JButton btn1=new JButton(”確定“);String strs=null,xxno,xscore;Statement stmt;ResultSet rs;ResultSetMetaData dbmd;public ex4_1(){ String sql=”select * from address “;try{ stmt=ConnectServer.con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);rs=stmt.executeQuery(sql);dbmd=rs.getMetaData();for(int i=1;i<=dbmd.getColumnCount();i++)title.addElement(dbmd.getColumnName(i));dtm=new DefaultTableModel(null,title);table=new JTable(dtm);initTable();table.setRowHeight(20);p1=new JScrollPane(table);btn1.addActionListener(this);p3.add(bq1);p3.add(combSs);p3.add(btn1);this.getContentPane().add(p3,”North“);this.getContentPane().add(p1,”Center“);}catch(Exception e){System.out.println(e);dispose();} this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0);}});setTitle(”學生信息查詢“);setSize(600,400);setVisible(true);} void initTable(){ dtm.setRowCount(0);try{ rs.beforeFirst();while(rs.next()){ Vector v1=new Vector();for(int i=1;i<=dbmd.getColumnCount();i++)v1.addElement(rs.getString(i));dtm.addRow(v1);} }catch(SQLException e){e.printStackTrace();} dtm.fireTableStructureChanged();} public void actionPerformed(ActionEvent e){ Vector title1=new Vector();if(e.getSource()==btn1){ strs=(String)combSs.getText();String sql=”select * from address where 姓名 LIKE '“+strs+”%'“;19 Java程序設計簡明教程 try{ stmt=ConnectServer.con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);rs=stmt.executeQuery(sql);dbmd=rs.getMetaData();for(int i=1;i<=dbmd.getColumnCount();i++)title1.addElement(dbmd.getColumnName(i));dtm=new DefaultTableModel(null,title1);table=new JTable(dtm);}catch(Exception ee){System.out.println(ee);dispose();} initTable();p1=new JScrollPane(table);this.getContentPane().add(p1,”Center“);setTitle(”學生信息“);table.setRowHeight(20);setSize(600,400);setVisible(true);} } public static void main(String args[]){ if(!ConnectServer.conn(”jdbc:odbc:xsgl“,”sa“,”“)){ JOptionPane.showMessageDialog(null,”數據庫連接不成功“);System.exit(0);} new ex4_1();} } 2.編寫一個應用程序,使其可以從一個數據庫的某個表中查詢一個列的所有信息?!緟⒖汲绦颉?/p> import java.awt.*;import java.sql.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import javax.swing.table.*;public class ex4_2 extends JFrame implements ActionListener{ JTable table;DefaultTableModel dtm;Vector title=new Vector();JScrollPane p1;JPanel p2=new JPanel();JPanel p3=new JPanel();JButton b1=new JButton(”首頁“);JButton b2=new JButton(”上頁“);JButton b3=new JButton(”下頁“);JButton b4=new JButton(”尾頁“);JLabel bb=new JLabel(” “);JButton btn1=new JButton(”查詢“);JComboBox combSs=new JComboBox();int count=0;int pagesize=6;int pagecount=0;20 上機練習題參考答案 int page=1;Statement stmt;ResultSet rs;ResultSetMetaData dbmd;public ex4_2(){ String sql=”select * from baseinf“;try{ stmt=ConnectServer.con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);rs=stmt.executeQuery(sql);count=getcount();pagecount=(int)count/pagesize+(count%pagesize==0?0:1);dbmd=rs.getMetaData();for(int i=1;i<=dbmd.getColumnCount();i++){ title.addElement(dbmd.getColumnName(i));combSs.addItem(dbmd.getColumnName(i));} dtm=new DefaultTableModel(null,title);table=new JTable(dtm);initTable();table.setRowHeight(20);p1=new JScrollPane(table);if(pagecount!=0)bb.setText(”第“+page+”頁“);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);btn1.addActionListener(this);p2.add(b1);p2.add(b2);p2.add(b3);p2.add(b4);p2.add(bb);p3.add(btn1);p3.add(combSs);this.getContentPane().add(p3,”North“);this.getContentPane().add(p1,”Center“);this.getContentPane().add(p2,”South“);}catch(Exception e){System.out.println(e);dispose();} this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ try{ rs.close();stmt.close();ConnectServer.con.close();System.exit(0);}catch(SQLException ee){ee.printStackTrace();} }});setTitle(”書目信息分頁瀏覽“);setSize(500,300);setVisible(true);} void initTable(){ dtm.setRowCount(0);try{ rs.beforeFirst();for(int i=1;i<1+pagesize*(page-1);i++)rs.next();int j=0;while(j Java程序設計簡明教程 j++;Vector v1=new Vector();for(int i=1;i<=dbmd.getColumnCount();i++)v1.addElement(rs.getString(i));dtm.addRow(v1);} }catch(SQLException e){e.printStackTrace();} dtm.fireTableStructureChanged();this.getContentPane();} public int getcount(){ int n=0;try{ if(rs.last()){ n=rs.getRow();rs.beforeFirst();return n;}else return 0;}catch(SQLException e){System.out.println(”有異常拋出“);return 0;} } public void actionPerformed(ActionEvent e){ Vector title1=new Vector();if(e.getSource()==btn1){ String strs=(String)combSs.getSelectedItem();String sql=”select no ,“+strs.trim()+” from baseinf“;try{ stmt=ConnectServer.con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);rs=stmt.executeQuery(sql);count=getcount();dbmd=rs.getMetaData();for(int i=1;i<=dbmd.getColumnCount();i++)title1.addElement(dbmd.getColumnName(i));dtm=new DefaultTableModel(null,title1);table=new JTable(dtm);}catch(Exception ee){System.out.println(ee);dispose();} initTable();p1=new JScrollPane(table);this.getContentPane().add(p1,”Center“);setTitle(”書目信息按某一列查詢?yōu)g覽“);this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0);}});setSize(500,300);setVisible(true);} else if(e.getSource()==b1)page=1;else if(e.getSource()==b2){if(page>1)page=page-1;} else if(e.getSource()==b3){if(page 第”+page+“頁