-2

ファイルを保存できる場所を選択できるパネルを作成します。Java のドキュメントを読んだところ、ファイル チューザーという名前のスイング コンポーネントがあることがわかりましたが、その使用方法がわかりません。作成したファイルを保存したマシンのパスを選択する必要があります。

4

2 に答える 2

2

それの使い方?まあ、あなたはただ「それを使う」必要があります!本当!

これにより、FileChooser インスタンスが作成され、ユーザーのデスクトップ フォルダーから開始するように設定されます。

JFileChooser fc = new JFileChooser(System.getProperty("user.home") + "/Desktop");

その後、さまざまなオプションを設定できます。この場合、複数のファイルを選択できるように設定していますが、「.xls」(Excel) ファイルのみを選択できます。

fc.setMultiSelectionEnabled(true);

SelectionEnabled(true);
        FileFilter ff = new FileFilter() {

            @Override
            public boolean accept(File f) {
                if (f.isDirectory()) {
                    return true;
                }
                String extension = f.getName().substring(f.getName().lastIndexOf("."));
                if (extension != null) {
                    if (extension.equalsIgnoreCase(".xls")) {
                        return true;
                    } else {
                        return false;
                    }
                }
                return false;
            }

            @Override
            public String getDescription() {
                return "Arquivos Excel (\'.xls\')";
            }
        };
fc.setFileFilter(ff);

そして最後に、私はそれを表示し、ユーザーの選択と選択したファイルを取得しています:

File[] chosenFiles;
int choice = fc.showOpenDialog(fc);
        if (choice == JFileChooser.APPROVE_OPTION) {
            chosenFiles = fc.getSelectedFiles();
        } else {
        //User canceled. Do whatever is appropriate in this case.
        }

楽しみ!そして成功を祈る!

于 2012-07-13T19:40:37.840 に答える
1

Oracle の Web サイトから直接入手できるこのチュートリアルは、FileChoosers について学習するのに最適な場所です。

final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);

if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    //This is where a real application would open the file.
    log.append("Opening: " + file.getName() + ".");
} else {
    log.append("Open command cancelled by user.");
}

上記のコードは FileChooser を開き、選択したファイルをfc変数に格納します。選択したボタン(OK、キャンセルなど)は に保存されreturnValます。その後、ファイルに対して必要な操作を行うことができます。

于 2012-07-13T19:34:59.273 に答える