隨筆-28  評論-51  文章-10  trackbacks-0
          以前雖然看了很多書,但是只重理論不重實踐,bebeyond說的沒錯,如果你不把知識內化,那么即使你讀的書再多,你的老師水平再高也于事無補,現代社會看能力啊。所以清明也懶得去玩了,靜下心,重頭再來!!這是第一篇
          [java重頭再來系列之一]java界面布局,文件操作,線程,事件響應
          源碼有200多行,若要顯示動畫(線程)需要5張gif圖片,但程序中有一個疑問,用紅色高亮顯示的update為何不會調用?如果把Animation類獨立出來(不繼承JPanel,而繼承JFrame),那是會首先調用update的啊。。。向高人求助


          FocusCrawler.java
            1 package kyle;
            2 
            3 import java.awt.BorderLayout;
            4 import java.awt.Color;
            5 import java.awt.Container;
            6 import java.awt.Dimension;
            7 import java.awt.Graphics;
            8 import java.awt.GridLayout;
            9 import java.awt.Image;
           10 import java.awt.MediaTracker;
           11 import java.awt.Toolkit;
           12 import java.awt.event.ActionEvent;
           13 import java.awt.event.ActionListener;
           14 import java.awt.event.WindowAdapter;
           15 import java.awt.event.WindowEvent;
           16 import java.io.BufferedReader;
           17 import java.io.BufferedWriter;
           18 import java.io.File;
           19 import java.io.FileReader;
           20 import java.io.FileWriter;
           21 import java.io.IOException;
           22 
           23 import javax.swing.JButton;
           24 import javax.swing.JFileChooser;
           25 import javax.swing.JFrame;
           26 import javax.swing.JLabel;
           27 import javax.swing.JPanel;
           28 import javax.swing.JScrollPane;
           29 import javax.swing.JTextArea;
           30 import javax.swing.filechooser.FileFilter;
           31 /*
           32  * 2008.3 fullfocus
           33  * 一個圖像界面的文件讀取,保存和動畫顯示
           34  * 主要涉及 界面設計,文件流讀取,線程應用,事件響應
           35  */
           36 public class FocusCrawler extends JFrame {
           37 
           38     private static JTextArea jarea;//文本內容顯示區
           39     private static JLabel jlbl;//文件名顯示區
           40     
           41     public FocusCrawler()
           42     {
           43 
           44         JPanel panelC = new JPanel(); //中心
           45         JPanel panelS = new JPanel();//
           46 
           47 
           48 
           49         
           50         setTitle("文件閱覽器");
           51         
           52 
           53         jarea = new JTextArea();
           54         JScrollPane scrollPane = new JScrollPane(jarea);//使文本可以滾動的方法
           55         
           56         jlbl = new JLabel("文件名");
           57         JButton openfile = new JButton("打開");
           58         JButton savefile = new JButton("保存");
           59         
           60         Container cp = getContentPane();
           61         
           62         /*添加頂部圖像區*/
           63         Animation ani = new Animation();
           64         ani.setVisible(true);
           65         ani.setPreferredSize(new Dimension(ani.getImageWidth(),ani.getImageHight())); //組件自身的大小優先級弱與layout的優先級,需指定setPreferredSize方可
           66         cp.add(ani,"North");
           67         /*添加中間文本顯示區*/
           68         panelC.setLayout(new BorderLayout());
           69         panelC.add(jlbl,"North");   
           70         panelC.add(scrollPane,"Center");
           71         cp.add(panelC,"Center");
           72         /*添加底下按鈕*/
           73 
           74          
           75          openfile.addActionListener(new ActionListener()
           76          {
           77 
           78             @Override
           79             public void actionPerformed(ActionEvent arg0) {
           80                 // TODO Auto-generated method stub
           81                 JFileChooser chooser = new JFileChooser();
           82                 TextFilter filter = new TextFilter();
           83                  chooser.setFileFilter(filter);
           84                 int returnVal = chooser.showOpenDialog(null);
           85                  if(returnVal == JFileChooser.APPROVE_OPTION) {
           86                     System.out.println("You chose to open this file: " +
           87                          chooser.getSelectedFile().getName());
           88                     File inputfile = chooser.getSelectedFile();
           89                     //文件名顯示在LABEL
           90                     FocusCrawler.jlbl.setText(inputfile.getAbsolutePath());
           91                     
           92                     try {
           93                         String line = null;
           94                         BufferedReader in = 
           95                             new BufferedReader(new FileReader(inputfile));
           96                         while( (line=in.readLine())!= null)
           97                         {
           98                             FocusCrawler.jarea.append(line + "\n");
           99                         }
          100                         in.close();
          101                     } catch (Exception e) {
          102                         // TODO Auto-generated catch block
          103                         e.printStackTrace();
          104                     }
          105                  }
          106             }
          107              
          108          });         
          109          savefile.addActionListener(new ActionListener()
          110          {
          111 
          112             @Override
          113             public void actionPerformed(ActionEvent arg0) {
          114                 // TODO Auto-generated method stub
          115                 File f = new File(FocusCrawler.jlbl.getText());
          116                 if(f.exists())
          117                 {
          118                     try {
          119                         BufferedWriter bw = new BufferedWriter(new FileWriter(f));
          120                         bw.write(FocusCrawler.jarea.getText());
          121                         FocusCrawler.jlbl.setText("works is done!!");
          122                         bw.close();
          123                     } catch (IOException e) {
          124                         // TODO Auto-generated catch block
          125                         e.printStackTrace();
          126                     }
          127                     
          128                 }
          129             }
          130              
          131          });    
          132         
          133         
          134         
          135         panelS.setLayout(new GridLayout(1,2));
          136         panelS.add(openfile); 
          137         panelS.add(savefile);
          138         cp.add(panelS,"South");
          139         
          140     }
          141 
          142     /**
          143      * @param args
          144      */
          145     public static void main(String[] args) {
          146         // TODO Auto-generated method stub
          147         System.out.println("hello world!");
          148         JFrame frame = new FocusCrawler();
          149         frame.setSize(500,500);
          150         frame.addWindowListener(new WindowAdapter(){
          151             
          152         public void windowClosing(WindowEvent e)
          153         {
          154             System.exit(0);
          155         }
          156         });
          157         frame.setVisible(true);
          158     }
          159 
          160 }
          161 
          162 class Animation extends JPanel implements Runnable
          163 {
          164 
          165     int totalNum = 5;
          166     int currentNum = 0;
          167     int x,x1;
          168     int delay = 100;
          169     Image images[];
          170     Thread animator;
          171     
          172     public Animation()
          173     {
          174         images = new Image[totalNum];
          175         Toolkit defaultTk = Toolkit.getDefaultToolkit();
          176         MediaTracker tracker = new MediaTracker(this);
          177         for(int i = 0; i < totalNum; i++)
          178         {
          179             images[i] = defaultTk.getImage("rene"+i+".gif");
          180             tracker.addImage(images[i], i);
          181             try {
          182                 tracker.waitForID(i);
          183             } catch (InterruptedException e) {
          184                 // TODO Auto-generated catch block
          185                 e.printStackTrace();
          186             }
          187         }
          188         x = 0;
          189         x1 = 0;
          190         animator = new Thread(this);
          191         animator.start();
          192     }
          193     @Override
          194     public void run() {
          195         // TODO Auto-generated method stub
          196         while(Thread.currentThread() == animator)
          197         {
          198             repaint();
          199             try {
          200                 Thread.sleep(delay);
          201             } catch (InterruptedException e) {
          202                 // TODO Auto-generated catch block
          203                 e.printStackTrace();
          204             }
          205         }
          206     }
          207 /*為什么這個方法得不到調用????   繼承JPanel 的原因?*/
          208 //    public void update(Graphics g)
          209 //    {
          210 //    System.out.println("update");//<<
          211 //        g.setColor(Color.yellow);
          212 //        g.fillRect(x1, 0, images[0].getWidth(this), images[0].getHeight(this));
          213 //        paint(g);
          214 //    }
          215     public void paint(Graphics g)
          216     {
          217 System.out.println("paint");//<<
          218         g.setColor(Color.yellow);
          219         g.fillRect(x1, 0, images[0].getWidth(this), images[0].getHeight(this));
          220         
          221         g.drawImage(images[currentNum], 10+x, 0this);
          222         x1 = x;
          223         x = (x+5)%400;
          224         currentNum = ++currentNum%totalNum;
          225     }
          226     
          227     public int getImageWidth()
          228     {
          229         return images[0].getWidth(this);
          230     }
          231     public int getImageHight()
          232     {
          233         return images[0].getHeight(this);
          234     }
          235 }
          236 
          237 
          238 /*文件選擇框只選擇TXT文件*/
          239 class TextFilter extends FileFilter
          240 {
          241 
          242     @Override
          243     public boolean accept(File f) {
          244         // TODO Auto-generated method stub
          245           String filename = f.getName();
          246             return filename.endsWith(".txt");
          247     }
          248 
          249     @Override
          250     public String getDescription() {
          251         // TODO Auto-generated method stub
          252         return  "*.txt";
          253     }
          254     
          255 }









          posted on 2008-04-06 14:23 fullfocus 閱讀(1900) 評論(1)  編輯  收藏 所屬分類: JAVA/J2EE

          評論:
          # re: [java重頭再來系列之一]java界面布局,文件操作,線程,事件響應 2008-04-06 15:47 | BeanSoft
          自定義JComponent組件時,應該覆蓋 paintComponent(Graphics g) 方法,而不是update()和paint(),因為JComponent繪制時要做很多工作。
          參考:http://www.java3z.com/cwbwebhome/article/pr/sw4.jsp  回復  更多評論
            
          主站蜘蛛池模板: 望都县| 伊吾县| 墨竹工卡县| 宜川县| 高密市| 宁都县| 项城市| 五原县| 肥乡县| 广东省| 泰兴市| 城固县| 会宁县| 新安县| 山东| 正安县| 仙居县| 镇巴县| 凤城市| 许昌县| 西峡县| 澎湖县| 库伦旗| 鹤山市| 博白县| 阜康市| 临西县| 宜都市| 荣成市| 贵州省| 库车县| 西藏| 祁连县| 和林格尔县| 桦南县| 平潭县| 稷山县| 尼木县| 新丰县| 石狮市| 黑山县|