仕切線(ディバイダ)の移動可能な最大値と最小値を取得する

広告

仕切線が移動可能な最小位置と最大位置を取得する方法を確認します。JSplitPaneクラスで用意されている「getMinimumDividerLocation」メソッドと「getMaximumDividerLocation」メソッドを使います。

Look & Feel の実装からディバイダの最小の位置を返します。

戻り値:
  最小の位置の UI 固有の値 (通常はピクセル数) を指定する int 値。 UI が
    null の場合は -1 (上文と一緒にしました)
Look & Feel の実装からディバイダの最大の位置を返します。

戻り値:
  最大の位置の UI 固有の値 (通常はピクセル数) を指定する int 値。 UI が
    null の場合は -1 (上文と一緒にしました)

戻り値として仕切線が移動可能な最小値と最大値をint型の値として取得できます。ここで取得できる値は仕切線の左側とスプリットペインの左端からの距離となります。

なお、このメソッドで取得できる値はスプリットペインが一度表示された後でないと正しい値を返してくれませんので注意して下さい。

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

JSplitPane splitpane = new JSplitPane();
int min = splitpane.getMinimumDividerLocation();
int max = splitpane.getMaximumDividerLocation();

サンプルプログラム

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

JSplitPaneTest7.java

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

public class JSplitPaneTest7 extends JFrame implements ActionListener{

  JSplitPane splitpane;
  JLabel minLabel;
  JLabel maxLabel;

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

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

  JSplitPaneTest7(){
    splitpane = new JSplitPane();

    JPanel leftPanel = new JPanel();
    JButton leftButton = new JButton("Left");
    leftPanel.add(leftButton);

    JPanel rightPanel = new JPanel();
    JButton rightButton = new JButton("Right");
    rightPanel.add(rightButton);

    splitpane.setLeftComponent(leftPanel);
    splitpane.setRightComponent(rightPanel);

    int min = splitpane.getMinimumDividerLocation();
    minLabel = new JLabel("min:" + min);
    int max = splitpane.getMaximumDividerLocation();
    maxLabel = new JLabel("max:" + max);

    JButton button = new JButton("get");
    button.addActionListener(this);

    JPanel labelPanel = new JPanel();
    labelPanel.add(minLabel);
    labelPanel.add(maxLabel);
    labelPanel.add(button);

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

  public void actionPerformed(ActionEvent e){
    int min = splitpane.getMinimumDividerLocation();
    minLabel.setText("min:" + min);
    int max = splitpane.getMaximumDividerLocation();
    maxLabel.setText("max:" + max);
  }
}

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

JSplitPaneで仕切線の最大位置と最小位置を取得する

起動直後は最小値は正しい値なのですが最大値は異なった値が取得されています。ではボタンをクリックして改めて取得して下さい。

JSplitPaneで仕切線の最大位置と最小位置を取得する

一度表示された後であれば正しい値を取得できます。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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