How do you stack buttons vertically on a JOptionPane with JDialogs?

I’m trying to stack three buttons vertically onto a JOptionPane using createDialog, but it’s not quite working with a GridLayout. Also, I’m not sure how to get rid of the ‘OK’ button as well. You’re probably wondering why I am doing it this way, but this is the way I was told to do it. I think I can use a JFrame, but I don’t think that goes well with a JOptionPane because that’s where I want the buttons stacked.

It should be like this:
| Need Help |
| Help Me |
| Counting |

I need accessibility to add action listeners at some point, but this seems to be getting to convoluted before I can even get to that point.

import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.*;
public class ThreeButtons {

    static JDialog dialog;
    public static void main(String[] args) {

        JOptionPane optionPane = new JOptionPane();
        optionPane.setMessage("Set Message");
        optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
        optionPane.setLayout(new GridLayout(3,1));
        String[] buttonTxt = {"Need Help","Help Me","Counting"};
        JButton[] buttons = new JButton[buttonTxt.length];
        for (int i = 0; i < buttonTxt.length; i++)
        {
            buttons[i] = new JButton(buttonTxt[i]); 
            optionPane.add(buttons[i]);
        }
        dialog = optionPane.createDialog(null, "Icon/Text Button");
        dialog.setVisible(true);

    }

}

Answer

If you want to stack the buttons you need to add them to a panel and add the panel to the option pane like this:

    JDialog dialog = null;
    JOptionPane optionPane = new JOptionPane();
    optionPane.setMessage("Set Message");
    optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);

    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(3,1));
    String[] buttonTxt = {"Need Help","Help Me","Counting"};
    JButton[] buttons = new JButton[buttonTxt.length];
    for (int i = 0; i < buttonTxt.length; i++)
    {
        buttons[i] = new JButton(buttonTxt[i]);
        panel.add(buttons[i]);
    }
    optionPane.setOptionType(JOptionPane.DEFAULT_OPTION);
    optionPane.add(panel);
    dialog = optionPane.createDialog(null, "Icon/Text Button");
    dialog.setVisible(true);

I’m not sure how you could get rid of the OK button though apart from manually going through the contents of the JOptionPane and removing it. You could always create your own JDialog then you have full control, but there will be slightly more work getting the nice joption pane icons 🙂