Search code examples
javaswingjoptionpane

How can I use a JSlider (or other JComponent) in a JOptionPane option dialog?


I have a UI in which I want to display a popup with a slider bar, with a message, and have the user be able to click OK or Cancel after choosing a value (or not). JOptionPane has various show methods that seem like they'd be useful, but I was unable to find much about making them do what I want.

This is actually a question that I had to root around to find an answer to, and I'll provide it below. I hope it will be useful to someone else.


Solution

  • The examples I was able to find had the standard flaw of examples: they weren't close enough to what I wanted to tell me how to do this, and didn't explain enough about how things worked to alter them on my own. I finally ran across a tutorial which explained that the "messages" in the dialog could be components, and the JOptionPane code would render them. This example uses a JSlider, I assume other JComponents could be used as well.

    The documentation also talks about what to do if you want to "display the dialog directly", but I never did figure out what they meant by that.

    I stumbled around in various forms of JOptionPane methods before figuring out the following:

    /**
     * display the dialog for entering the number of spots to move the first
     * marble chosen after a 7 is played. Returns 0 if the user cancelled this
     * operation.
     */
    @Override
    public int getMoveCount()
    {
        int moveCount = 0;
    
        JSlider slider = createSlider();
        JPanel sliderPanel = createSliderPanel("myMessage", slider);
        String title = "myTitle"; 
        int dialogResponse = JOptionPane.showOptionDialog
                (this,                  // I'm within a JFrame here
                 sliderPanel,
                 title,
                 JOptionPane.OK_CANCEL_OPTION,
                 JOptionPane.QUESTION_MESSAGE,
                 null, null, null
                );
        if (JOptionPane.OK_OPTION == dialogResponse) 
             { moveCount = slider.getValue(); }
        else { moveCount = 0; } // works for cancel button, red 'x', and keyboard escape key
    
        return moveCount;
    }
    
    private JSlider createSlider()
    {
        JSlider slider = new JSlider(1,7);
        slider.setMajorTickSpacing(1);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.setValue(7);                // default to 7
    
        return slider;
    }