選択されている項目を取得する

広告

スピナーで現在選択されている項目(表示されている項目)を取得する方法を確認します。SpinnerNumberModelクラスで用いされている「getValue」メソッドを使います。

シーケンスの現在の要素の値を返します。

戻り値:
  value プロパティー

戻り値として現在スピナーで選択されている項目をObjectクラスのオブジェクトとして取得します。IntegerクラスやDoubleクラスのオブジェクトなどに変換して利用します。

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

SpinnerNumberMod model = new SpinnerNumberMod(0, null, null, 1);
JSpinner spinner = new JSpinner(model);

Integer value = (Integer)model.getValue();

サンプルプログラム

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

JSpinnerTest13.java

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

public class JSpinnerTest13 extends JFrame implements ActionListener{

SpinnerNumberModel model;

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

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

  JSpinnerTest13(){

    model = new SpinnerNumberModel(0, null, null, 1);

    JSpinner spinner = new JSpinner(model);
    spinner.setPreferredSize(new Dimension(100, 25));

    JPanel p = new JPanel();
    p.add(spinner);

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

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

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

  public void actionPerformed(ActionEvent e){
    Integer value = (Integer)model.getValue();

    JOptionPane.showMessageDialog(this, "Value = " + value.intValue());
  }
}

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

SpinnerNumberModelで選択されている値を取得する

スピナーで値を選択し、画面下部のボタンをクリックすると現在選択されている値を取得してダイアログに表示します。

SpinnerNumberModelで選択されている値を取得する

SpinnerNumberModelで選択されている値を取得する

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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