我尝试创建基于JFrame
的简单GUI,允许用户在点击某些JButton
后显示特定目录中的所有.txt文件并打印此" 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();
}
}
答案 0 :(得分:0)
JTextArea
代替JTextField
进行新行打印。System.out.println
使用setText
JTextArea
setVisible(true)
和setSize(400,400)
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();
}
}