2012-06-11 51 views

回答

1

你的問題還不清楚,但我假設你想要的JTextArea中添加到JFileChooser中,以便它可以像文件預覽面板。

您可以使用setAccessory()方法將JTextArea添加到JFileChooser。

tutorial on JFileChooser這個tutorial on JFileChooser顯示瞭如何做一些類似的地方,其中附件顯示來自文件的圖像而不是來自文件的文本。

您需要小心處理文件不包含文本或太大,或者由於權限等原因無法打開的文件。需要花費很多精力才能獲得文件對。

+0

我喜歡這個答案,因爲這給了我方向,因爲在此之前我誤解了整個事情:-) –

2

這裏找到一個示例程序,爲您提供幫助,但如果要讀取的文件很長,那麼總是ta柯SwingWorker幫助:

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

public class ReadFileExample 
{ 
    private BufferedReader input; 
    private String line; 
    private JFileChooser fc; 

    public ReadFileExample() 
    { 
     line = new String(); 
     fc = new JFileChooser();   
    } 

    private void displayGUI() 
    { 
     final JFrame frame = new JFrame("Read File Example"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     final JTextArea tarea = new JTextArea(10, 10);  

     JButton readButton = new JButton("OPEN FILE"); 
     readButton.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent ae) 
      { 
       int returnVal = fc.showOpenDialog(frame); 

       if (returnVal == JFileChooser.APPROVE_OPTION) { 
        File file = fc.getSelectedFile(); 
        //This is where a real application would open the file. 
        try 
        { 
         input = new BufferedReader(
           new InputStreamReader(
           new FileInputStream(
           file))); 
         tarea.read(input, "READING FILE :-)");  
        } 
        catch(Exception e) 
        {  
         e.printStackTrace(); 
        } 
       } else { 
        System.out.println("Operation is CANCELLED :("); 
       } 
      } 
     }); 

     frame.getContentPane().add(tarea, BorderLayout.CENTER); 
     frame.getContentPane().add(readButton, BorderLayout.PAGE_END); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String... args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       new ReadFileExample().displayGUI(); 
      } 
     }); 
    } 
} 
+0

請確實看看第2點,我懷疑,我編輯的鏈接是正確的還是不是! –

相關問題