我对编程相当陌生,我刚刚编写了一个小程序程序,它应该列出目录中的文件。该小程序在 Eclipse 中运行良好,但问题是当我尝试在 GUI 加载的浏览器中运行该小程序时,该小程序不会像在 Eclipse 中那样响应。任何帮助将不胜感激。:)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JApplet;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class DirReader extends JApplet{
private JTextArea outputWindow;
private JTextField dirPath;
private String path;
private Font font;
private File folder;
private File[] listOfFiles;
public void init(){
font = new Font("Times New Roman", Font.PLAIN, 16);
dirPath = new JTextField("Enter Directory Path");
dirPath.setFont(font);
outputWindow = new JTextArea();
outputWindow.setEditable(false);
outputWindow.setFont(font);
outputWindow.setBackground(Color.DARK_GRAY);
outputWindow.setForeground(Color.ORANGE);
add(dirPath, BorderLayout.NORTH);
add(outputWindow, BorderLayout.CENTER);
setSize(400,750);
dirPath.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event) {
path = dirPath.getText();
folder = new File(path);
listOfFiles = folder.listFiles();
System.out.println("Directory path set");
ListOfFiles();
}
}
);
System.out.println("Progam Intilized:");
}
public void ListOfFiles(){
outputWindow.setText(null);
try{
for(int counter = 0 ; counter < listOfFiles.length ; counter++ ){
if(listOfFiles[counter].isFile()){
outputWindow.append("[FILE] " + listOfFiles[counter].getName()+ "\n");
System.out.println("[FILE] " + listOfFiles[counter].getName());
}
else if(listOfFiles[counter].isDirectory()){
outputWindow.append("[DIR] " + listOfFiles[counter].getName() + "\n");
System.out.println("[DIR] " + listOfFiles[counter].getName());
}
}
}catch(Exception e){
System.out.println("Error: Directory could not be found.");
outputWindow.setText("Error: Could not find directory.");
}
}
}