显示路径的两个jcombobox选项

时间:2015-01-26 16:01:06

标签: java directory jcombobox subdirectory

我需要显示两个带目录名的连接组合框。有一个包含多个目录的起始路径,这些目录显示在第一个jcombobox中,当选择目录时,子目录需要显示在第二个jcombobox中。第二个jcombobox应该能够选择其中一个子目录。每个子子目录包含多个.txt文件。我设法在两个jcomboboxes上显示目录和子目录,包括文件。

package calc.my.pay;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JComboBox;
import java.awt.Color;
import javax.swing.JTable;
import javax.swing.JScrollPane;

public class CalcMyPay extends JFrame implements ActionListener {

    private JPanel contentPane;
    private JScrollPane scrollPane;
    private JComboBox folderSelector, subFolderSelector;
    private File[] directory, subDirectory;

    private String subPath, finalSubPath, selectedSubDirectory, finalSubDirectory;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CalcMyPay frame = new CalcMyPay();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     * @throws IOException 
     */

    public CalcMyPay() 
    {   
        setBackground(Color.LIGHT_GRAY);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(350, 10, 1000, 700);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        scrollPane = new JScrollPane();
        scrollPane.setBounds(12, 120, 958, 300);

        String startPath = "C:/Users/Zeus/Desktop/Content/";

        // The starting path of the file
        directory = new File(startPath).listFiles();

        // Folders dropdown box
        folderSelector = new JComboBox();
        folderSelector.setBounds(60, 13, 200, 22);
        folderSelector.insertItemAt("Choose directory", 0);
        folderSelector.setSelectedIndex(0);
        for(int i=0; i < directory.length; i++) {
            System.out.println(directory[i]);
            folderSelector.addItem(directory[i].getName());
        }
        contentPane.add(folderSelector);

        // Sub folder dropdown box
        subFolderSelector = new JComboBox();
        subFolderSelector.setBounds(300, 13, 200, 22);
        subFolderSelector.insertItemAt("Choose subdirectory", 0);
        subFolderSelector.setSelectedIndex(0);
        contentPane.add(subFolderSelector);

        folderSelector.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // Get the folder dropdown selected item
                selectedSubDirectory = folderSelector.getSelectedItem().toString();
                //System.out.println("Folder selected: " + Arrays.asList(directory).toString().contains(selectedSubDirectory));
                //System.out.println("Subfolders based on folder selected : " + Arrays.asList(directory) + "         " + selectedSubDirectory);
                //subFolderSelector.addItem(folderSelector.getSelectedItem());

                // Check if the array from the main directory contains the selected directory
                if(Arrays.asList(directory).toString().contains(selectedSubDirectory)) {
                    // Make a new file that list all the directories in the given path
                    subPath = startPath + selectedSubDirectory;
                    subDirectory = new File(subPath).listFiles();
                    // Sort the array directory in a descending order
                    Arrays.sort(subDirectory, Collections.reverseOrder());
                    // Delete the previous list items, if any
                    subFolderSelector.removeAllItems();
                    // Iterate through all the directories in the selected folder
                    for(int i=0; i < subDirectory.length; i++) {
                        // Pass only directories (files will be omitted)
                        // ### Should check if directory contains only 4 numbers here
                        if(subDirectory[i].isDirectory()) {
                        //subFolderSelector.addItem(folderSelector.getSelectedItem());
                            subFolderSelector.addItem(subDirectory[i].getName());
                        }
                    }

                }
            }
        });

        subFolderSelector.addActionListener(new ActionListener() {
            int count = 0;
            @Override
            public void actionPerformed(ActionEvent e) {
                count++;
                if(count == 3) {
                    selectedSubSubDirectory = subFolderSelector.getSelectedItem().toString();

                    // Make an new file that list all the file in the selected sub folder
                    if(Arrays.asList(subDirectory).toString().contains(selectedSubDirectory)) {
                        //textFiles = new File(finalSubPath).listFiles();

                        subSubPath = startPath + selectedSubDirectory + "/" + selectedSubSubDirectory;
                        textFiles = new File(subSubPath).listFiles();

                        for(File file: textFiles) {
                            if(file.isFile() && file.toString().toLowerCase().endsWith("_110.txt")) {
                                System.out.println(file);
                            }
                        }
                    }
                    count = 0;
                }
            }
        });   
    }
}

但是你可以在subDirectorySelector的第二个actionListener中看到我有一个计数器。那里的代码执行三次(因为第二个jcombobox改变了值)。如果在第一个jcombobox中选择相同的路径两次,则会出错。必须有更好(可能)更短的方法来做到这一点。你会改变什么?

由于

1 个答案:

答案 0 :(得分:0)

我尝试制作自己的版本,但它非常相似,只是在更新subFolder选择器之前删除了actionListener,并添加了更多检查。

这是我的代码:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class ComboDemo extends JFrame implements ActionListener {

    private String rootDir;
    private JComboBox box1;
    private JComboBox box2;

    /**
     * Create the frame.
     */
    public ComboDemo () {
        super("Demo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        createGui();
        this.rootDir = "/home";
        setRootDir(new File(this.rootDir));
    }

    /**
     * Create the gui components.
     */
    private void createGui () {
        this.box1 = new JComboBox();
        this.box2 = new JComboBox();
        this.box1.addActionListener(this);
        this.box2.addActionListener(this);

        this.box1.insertItemAt("Choose directory :", 0);
        this.box1.setSelectedIndex(0);
        this.box2.insertItemAt("Choose subdirectory :", 0);
        this.box2.setSelectedIndex(0);

        setLayout(new FlowLayout(FlowLayout.LEADING));
        add(this.box1);
        add(this.box2);
    }

    /**
     * Show the gui.
     */
    private void showGui () {
        setSize(500, 250);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    /**
     * Update the first selector with the directories listed under the specified
     * root directory.
     * 
     * @param dir
     *            Root directory.
     */
    private void setRootDir (File dir) {
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                this.box1.addItem(file.getName());
            }
        }
    }

    @Override
    public void actionPerformed (ActionEvent e) {
        if (e.getSource() instanceof JComboBox) {
            JComboBox box = (JComboBox) e.getSource();

            // Box 1
            if (this.box1.equals(box)) {
                String dirName = box.getSelectedItem().toString();
                // RootDir / Folder
                File dir = new File(this.rootDir + File.separator + dirName);
                System.out.println("# Folder : " + dir.getPath());

                // Check if there is a least one file
                if (dir.exists() && dir.listFiles().length > 0) {
                    Arrays.sort(dir.listFiles(), Collections.reverseOrder());

                    // Reset box2
                    this.box2.removeAllItems();
                    this.box2.insertItemAt("Choose subdirectory :", 0);

                    // Update Box2
                    this.box2.removeActionListener(this);
                    for (File file : dir.listFiles()) {
                        if (file.isDirectory()) {
                            this.box2.addItem(file.getName());
                        }
                    }
                    this.box2.addActionListener(this);
                    this.box2.setSelectedIndex(0);
                }
            }
            // Box 2
            else if (this.box2.equals(box)) {
                // Check if box2 is empty
                if (box.getItemCount() > 0) {
                    String dirName = box.getSelectedItem().toString();
                    // RootDir / Folder / SubFolder
                    File dir = new File(this.rootDir + File.separator + this.box1.getSelectedItem().toString()
                            + File.separator + dirName);
                    System.out.println("# SubFolder : " + dir.getPath());

                    // Check if there is a least one file
                    if (dir.exists() && dir.listFiles().length > 0) {
                        Arrays.sort(dir.listFiles(), Collections.reverseOrder());

                        // Print .txt files
                        for (File file : dir.listFiles()) {
                            if (file.isFile() && file.getName().endsWith(".txt")) {
                                System.out.println("\t" + file.getName());
                            }
                        }
                    }
                }
            }
        }
    }

    public static void main (String[] args) {
        ComboDemo demo = new ComboDemo();
        demo.showGui();
    }
}