How to make a button that, when clicked, opens the

2020-02-13 03:24发布

问题:

I have made a button, but I don't now how to make it open a specific directory like %appdata% when the button is clicked on.

Here is the code ->

//---- button4 ----
        button4.setText("Texture Packs");
        button4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                JFileChooser fileChooser=new JFileChooser("%appdata%");
                int status = fileChooser.showOpenDialog(this);
                fileChooser.setMultiSelectionEnabled(false);

                if(status == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    // do something on the selected file.
                }


            }

And I want to make something like this ->

private void button4MouseClicked(MouseEvent e) throws IOException {

           open folder %appdata% 
           // Open the folder in the file explorer not in Java.
           // When I click on the button, the folder is viewed with the file explorer on the screen
        }

回答1:

import java.awt.Desktop;
import java.io.File;

public class OpenAppData {

    public static void main(String[] args) throws Exception {
        // Horribly platform specific.
        String appData = System.getenv("APPDATA");
        File appDataDir = new File(appData);
        // Get a sub-directory named 'texture'
        File textureDir = new File(appDataDir, "texture");
        Desktop.getDesktop().open(textureDir);
    }
}


回答2:

Execute a command using Runtime.exec(..). However, not every OS has the same file explorer, so you need to handle the OS.

Windows: Explorer /select, file

Mac: open -R file

Linux: xdg-open file

I wrote a FileExplorer class for the purpose of revealing files in the native file explorer, but you'll need to edit it to detect operating system. http://textu.be/6

NOTE: This is if you wish to reveal individual files. To reveal directories, Desktop#open(File) is far simpler, as posted by Andrew Thompson.



回答3:

If you are using Windows Vista and higher, System.getenv("APPDATA"); will return you C:\Users\(username}\AppData\Roaming, so you should go one time up, and use this path for filechooser, Just a simple modified Andrew's example,

    String appData = System.getenv("APPDATA");
    File appDataDir = new File(appData); // TODO: this path should be changed! 
    JFileChooser fileChooser = new JFileChooser(appData);
    fileChooser.showOpenDialog(new JFrame());

More about windows xp, and windows vista/7/8