Java Swing中的JButton(用于浏览PC文件夹)

7
我想在Swing中创建一个“浏览”按钮,当用户点击“浏览”按钮时,他应该能够从硬盘文件夹中选择一个位置来保存文件。这是我的界面设计的一部分。我该怎么做?
我希望路径能够显示在浏览按钮旁边的文本框中。
2个回答

5
...
public String fileID;
public JTextField txtField; //Assume this is the text box you placed beside browse button
public JButton btnBrowse = JButton("Browse");

public void actionPerformed(ActionEvent e)
{
    if (e.getSource() == btnBrowse)
    {
        chooser = new JFileChooser(new File(System.getProperty("user.home") + "\\Downloads")); //Downloads Directory as default
        chooser.setDialogTitle("Select Location");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);

        if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
        { 
            fileID = chooser.getSelectedFile().getPath();
            txtField.setText(fileID);
        }
    }
}
...

5

您应该查看Sun公司的教程,了解JFileChooser API。这将为您提供几乎所有您需要完成所需操作的内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接