一个界面有一个JComboBox和一个JTextArea,再无其他组件,不需要选择文件。一个JComboBox的选项对应一个文件。
给JComboBox添加消息映射,根据JComboBox的选项来确定读取哪一个文件并将读取到的内容逐行显示到JTextArea里。
希望诸位大侠帮忙写一个方法!!急!

解决方案 »

  1.   

    我这里有一个从文本文件中读取内容到JTextArea的例子,但是文件不是从JCombobox中选择的,而是从JFileChooser中选取的,你可以改一下
    [code]
    f = new JFrame();
     jta = new JTextArea(30,80);
     jta.getDocument().addDocumentListener(this);
     jta.addKeyListener(this);
     jta.addCaretListener(this);  jlb = new JLabel("");
     
     jsp = new JScrollPane(jta,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
     
     jta.setLineWrap(true);
     //jta.setWrapStyleWord(true);
     
     contentPane = f.getContentPane();
       contentPane.setLayout(gbl);
       
       contentPane.add(jsp);
       contentPane.add(jlb);
       
       gbl.setConstraints(jlb, new GridBagConstraints(10,10,1,1,0,0,GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(5,5,5,5),0,0));
       gbl.setConstraints(jsp, new GridBagConstraints(10,20,1,1,0,0,GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(5,5,5,5),0,0));
     
       String line = null; 
       
       InputStream inputStream = new FileInputStream(file);  
       byte[] head = new byte[3];  
       inputStream.read(head);   
       String code = "";  
        
       code = "gb2312";  
       if (head[0] == -1 && head[1] == -2 )  
       code = "UTF-16";  
       if (head[0] == -2 && head[1] == -1 )  
       code = "Unicode";  
       if(head[0]==-17 && head[1]==-69 && head[2] ==-65)  
       code = "UTF-8";      BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),code));
       
         content = "";
         
     while((line = in.readLine())!= null) //read until the end of file
     {
     if(line.trim().length()>0)
     {
     content = content + line;
     }
     } 
     
     String content_trim = content.replaceAll("[  ]","");//"[\\s*\\t\\n\\r]","");
     
     int x;
     content_new = "";
     
     for(x=1;x<=content_trim.length();x++)
     {
     
     if(x%74 !=0)
     {
     content_new = content_new + content_trim.substring(x-1, x);
     }
     else if(x%74 ==0)
     {
     content_new = content_new + "\n" + "\n";
     }  }
     
     jta.setText(content_new);
     jta.setCaretPosition(0);
     
     f.pack();
     f.setVisible(true);
     f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
     f.setAlwaysOnTop(true);
     
     f.setLocationRelativeTo(null);
    [code]