6

I need to put a JSpinner in a JOptionPane. Here is what I've tried:

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;

    public static void main(String[] args) {
        SpinnerNumberModel sModel = new SpinnerNumberModel(0, 0, 30, 1);
        JSpinner spinner = new JSpinner(sModel);
        JOptionPane.showInputDialog(spinner);
    }

Which results in:

enter image description here

How do I remove the textbox?

David
  • 15,652
  • 26
  • 115
  • 156

1 Answers1

14

You have to use showMessageDialog.

SpinnerNumberModel sModel = new SpinnerNumberModel(0, 0, 30, 1);
JSpinner spinner = new JSpinner(sModel);
JOptionPane.showMessageDialog(null, spinner);

For still having a cancel button, use:

int option = JOptionPane.showOptionDialog(null, spinner, "Enter valid number", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
if (option == JOptionPane.CANCEL_OPTION)
{
    // user hit cancel
} else if (option == JOptionPane.OK_OPTION)
{
    // user entered a number
}

Here is a screenshot on OS X:

enter image description here

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • @MartjinCourteaux Thank you. Would it be possible to add text too (like "Please enter a valid number:", or do I need to use a JPanel for that? – David Apr 11 '12 at 14:00
  • Two options for adding text: Set it as Dialog title, or add (as you already pointed out) a JPanel with the two components: the label and the spinner. – Martijn Courteaux Apr 11 '12 at 14:02
  • @MartjinCourteaux ok. One more thing - I still need the cancel button. What do you suggest? – David Apr 11 '12 at 14:03