【问题标题】:Two jcombobox options displaying path显示路径的两个 jcombobox 选项
【发布时间】:2015-03-25 02:00:13
【问题描述】:

我需要显示两个带有目录名称的连接组合框。 There is a start path which contains multiple directories that are displayed in the first jcombobox, and when a directory is selected, the sub directories need to be displayed in the second jcombobox.第二个 jcombobox 应该能够选择这些子目录之一。每个子子目录都包含多个 .txt 文件。我设法在包括文件在内的两个 jcombobox 上显示目录和子目录。

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 中看到的那样,我有一个计数器。那里的代码执行了 3 次(因为第二个 jcombobox 改变了值)。如果在第一个 jcombobox 中两次选择相同的路径,则会出现错误。必须有更好的(并且可能)更短的方法来做到这一点。你会改变什么?

谢谢

【问题讨论】:

    标签: java directory jcombobox subdirectory


    【解决方案1】:

    我尝试制作自己的版本,但它真的很相似,除了我在更新 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();
        }
    }
    

    【讨论】:

    • 谢谢,我想这是解决相同问题的另一种方法。多个 if 确实很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    相关资源
    最近更新 更多