Java Swing ComboBox list of files from unix machine

只谈情不闲聊 提交于 2020-01-16 14:32:12

问题


I'm running my first simple Java Swing application from my UNIX environment. Currently it has an image and some buttons that do random things - one of which executes a command to my UNIX shell.

I have a list of ".ksh" files in one of my directories on the UNIX machine that I'd like to read into a Swing GUI ComboBox.

The dropdown items will populate from the list of files in the directory on the UNIX machine, and when i click a file from the list, it will execute the script in the UNIX shell. The I'm not quite sure how to start.


回答1:


This way you could get the list of the files (as string array) with the extension ".ksh":

File dir = new File(pathToDir);
String[] files;
FilenameFilter filter = new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return !name.endWith(".ksh");
    }
};
files = dir.list(filter);

Then iterate the array and add the names to it.

To execute a command on shell, see one of these many answers




回答2:


Try something like this:

private JComboBox myComboBox = new JComboBox();
private void showFiles(){
    String myPath = "writeYourPathHere..."
    File folder = new File(myPath);
    File[] listOfFiles = folder.listFiles();
    for (int i = 0; i < listOfFiles.length; i++) {
        myComboBox.addItem(listOfFiles[i].getName());
    }
}

Once you select a file from the combobox

    private void selectedFile(){
    myComboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        //do something
        }
    });
}


来源:https://stackoverflow.com/questions/5601622/java-swing-combobox-list-of-files-from-unix-machine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!