Java 桌面应用收纳管理器代码示例 - 文件整理工具
以下是一个简单的 Java 桌面应用收纳管理器的代码示例,它使用 Swing 库创建一个简单的图形用户界面。用户可以输入一个目录路径,并点击'整理'按钮获取该目录下的所有文件名,并在窗口中显示。如果目录不存在或不是一个有效的目录,会弹出一个错误提示框。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class OrganizerApp extends JFrame {
private JTextField directoryTextField;
private JTextArea filesTextArea;
public OrganizerApp() {
super('收纳管理器');
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
JLabel directoryLabel = new JLabel('目录:');
directoryTextField = new JTextField(20);
JButton organizeButton = new JButton('整理');
organizeButton.addActionListener(new OrganizeButtonListener());
topPanel.add(directoryLabel);
topPanel.add(directoryTextField);
topPanel.add(organizeButton);
filesTextArea = new JTextArea();
filesTextArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(filesTextArea);
add(topPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
}
private class OrganizeButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String directoryPath = directoryTextField.getText();
File directory = new File(directoryPath);
if (directory.exists() && directory.isDirectory()) {
StringBuilder filesText = new StringBuilder();
File[] files = directory.listFiles();
for (File file : files) {
filesText.append(file.getName()).append('
');
}
filesTextArea.setText(filesText.toString());
} else {
JOptionPane.showMessageDialog(OrganizerApp.this, '目录不存在', '错误', JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
OrganizerApp app = new OrganizerApp();
app.setVisible(true);
}
});
}
}
你可以将以上代码保存为 OrganizerApp.java 文件,并编译运行它来查看效果。
原文地址: https://www.cveoy.top/t/topic/jDcR 著作权归作者所有。请勿转载和采集!