我们这节课练习的作业是从硬盘中扫描指定位置的文件再将其显示到图形用户界面中。在本节课的作业中主要运用了两部分的知识,一部分是GUI界面,我添加了一个列表框,一个下拉菜单,还有一个组合框,但是利用组合框进行分类的功能没有实现。另一部分的知识
package test.com;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
public class FileUtils {
private static final String FILES_DIR = "audio";
public FileUtils(){
String[] fileNames = findFiles(FILES_DIR, null);
makeFrame(fileNames);
}
public void makeFrame(String[] autoNames){
JFrame frm = new JFrame();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(6, 10, 10, 10));
contentPane.setLayout(new BorderLayout(5, 5));
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout(8, 8));
JLabel label = new JLabel("File lists");
label.setFont(new Font("Serif",Font.PLAIN,16));
JList fileList = new JList(autoNames);
fileList.setForeground(Color.BLACK);
fileList.setBackground(Color.green);
fileList.setSelectionBackground(new Color(87,49,134));
fileList.setSelectionForeground(new Color(140,171,226));
JScrollPane scrollPane = new JScrollPane(fileList);
scrollPane.setColumnHeaderView(label);
pane.add(scrollPane, BorderLayout.CENTER);
contentPane.add(pane, BorderLayout.CENTER);
frm.add(contentPane);
frm.setBounds(500,300,300,400);
frm.setVisible(true);
}
private String[] findFiles(String dirName, String suffix) {
File dir = new File(dirName);
if(dir.isDirectory()) {
String[] allFiles = dir.list();
if(suffix == null) {
return allFiles;
}
else {
List<String> selected = new ArrayList<String>();
for(String filename : allFiles) {
if(filename.endsWith(suffix)) {
selected.add(filename);
}
}
return selected.toArray(new String[selected.size()]);
}
}
else {
System.out.println("Error: " + dirName + " must be a directory");
return null;
}
}
public static void main(String[] args) {
new FileUtils();
}
}