Approveボタンに表示されるヒントを設定する

広告

Approveボタンに表示されるヒントを設定する方法を確認します。設定するにはJFileChooserクラスで用意されている「setApproveButtonToolTipText」メソッドを使います。

ApproveButton で使用されるツールヒントテキストを設定します。null の場合、
UI オブジェクトがボタンのテキストを決めます。

パラメータ:
  toolTipText - ApproveButton のツールヒントテキスト

引数にはApproveボタンに表示したいヒントを表すString型の値を設定します。

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

JFileChooser filechooser = new JFileChooser();
filechooser.setApproveButtonToolTipText("選択したファイルを開く");

int selected = filechooser.showOpenDialog(this);

サンプルプログラム

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

JFileChooserTest16.java

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

public class JFileChooserTest16 extends JFrame implements ActionListener{

  JLabel label;

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

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

  JFileChooserTest16(){
    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("c:\\temp");

    String tip = "選択したファイルを開く";
    filechooser.setApproveButtonToolTipText(tip);

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

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

JFileChooserでボタンに表示されるヒントを設定する

ボタンをクリックするとダイアログが表示されます。表示されたダイアログのApproveボタンにマウスを合わせて下さい。設定したヒントが表示されます。

JFileChooserでボタンに表示されるヒントを設定する

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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