打印JFrame中的文件列表

时间:2015-04-15 07:50:33

标签: java swing

我尝试创建基于JFrame的简单GUI,允许用户在点击某些JButton后显示特定目录中的所有.txt文件并打印此&#​​34; list& #34;将文件名转换为JTextField中的某些JFrame。我是Java编程领域的新手,所以请你帮助我。

package inputOutputProgram;

import java.awt.FlowLayout;
import java.awt.Font;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class ProjectGUI extends JFrame {

JLabel label;
static JTextField tf;
JButton button;

public ProjectGUI() {       
    tf = new JTextField(10);
    add(tf);

}

void showFiles() {
      String path = "C:\\Users\\data"; 

      String files;
      File folder = new File(path);
      File[] listOfFiles = folder.listFiles(); 

      for (int i = 0; i < listOfFiles.length; i++) 
      {

       if (listOfFiles[i].isFile()) 
       {
       files = listOfFiles[i].getName();
           if (files.endsWith(".txt") || files.endsWith(".TXT"))
           {
              System.out.println(files);
            }
         }
      }
}


 public static void main(String[] args) {
     ProjectGUI print = new ProjectGUI();

     print.showFiles();
    }
}

1 个答案:

答案 0 :(得分:0)

  1. 使用JTextArea代替JTextField进行新行打印。
  2. 而不是System.out.println使用setText
  3. JTextArea
  4. 使JFrame可见调用setVisible(true)setSize(400,400)
  5. package inputOutputProgram;

    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.io.File;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextArea;
    
    
    public class ProjectGUI extends JFrame {
    
    JLabel label;
    static JTextArea tf;
    JButton button;
    
    public ProjectGUI() {
    
    
        tf = new JTextArea();
        add(tf);
    
        // set visible JFrame with some size (400x400)
        setSize(400,400);
        setVisible(true);
    
    }
    
    void showFiles() {
          String path = "C:\\Users\\data"; 
    
          String files;
          String fileNames = "";
          File folder = new File(path);
          File[] listOfFiles = folder.listFiles(); 
    
          for (int i = 0; i < listOfFiles.length; i++) 
          {
    
           if (listOfFiles[i].isFile()) 
           {
           files = listOfFiles[i].getName();
               if (files.endsWith(".txt") || files.endsWith(".TXT"))
               {
                  fileNames += "\n" + files;
                }
            }
          }
          tf.setText( fileNames );
    }
    
    
     public static void main(String[] args) {
    
         ProjectGUI print = new ProjectGUI();
    
         print.showFiles();
    
        }
    }