ダイアログのタイトルを設定する

広告

ダイアログのタイトルを設定する方法を確認します。JFileChooserクラスで用意されている「setDialogTitle」メソッドを使います。

JFileChooser ウィンドウのタイトルバーに表示される文字列を設定します。

パラメータ:
  dialogTitle - タイトルバーの新しい String

引数にダイアログのタイトルとして表示される文字列をString型の値で指定します。

実際の使い方は次のようになります。

JFileChooser filechooser = new JFileChooser();
filechooser.setDialogTitle("名前を付けて保存");

int selected = filechooser.showSaveDialog(this);

サンプルプログラム

では簡単なサンプルを作成して試してみます。

JFileChooserTest8.java

import javax.swing.*;
import java.io.File;
import java.awt.BorderLayout;
import java.awt.event.*;

public class JFileChooserTest8 extends JFrame implements ActionListener{

  JLabel label;

  public static void main(String[] args){
    JFileChooserTest8 frame = new JFileChooserTest8();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(10, 10, 300, 200);
    frame.setTitle("タイトル");
    frame.setVisible(true);
  }

  JFileChooserTest8(){
    JButton button = new JButton("file select");
    button.addActionListener(this);

    JPanel buttonPanel = new JPanel();
    buttonPanel.add(button);

    label = new JLabel();

    JPanel labelPanel = new JPanel();
    labelPanel.add(label);

    getContentPane().add(labelPanel, BorderLayout.CENTER);
    getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
  }

  public void actionPerformed(ActionEvent e){
    JFileChooser filechooser = new JFileChooser();
    filechooser.setDialogTitle("名前を付けて保存");

    int selected = filechooser.showSaveDialog(this);
    if (selected == JFileChooser.APPROVE_OPTION){
      File file = filechooser.getSelectedFile();
      label.setText(file.getName());
    }
  }
}

上記をコンパイルした後で実行すると次のように表示されます。

JFileChooserでダイアログのタイトルを設定する

ボタンをクリックすると指定したタイトルを持つダイアログが表示されます。

JFileChooserでダイアログのタイトルを設定する

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。