2

I'm trying to put a TextBox & a Button in a JOptionPane.showOptionDialog horizontally. I've used this code.

JTextField txt = new JTextField();
JButton btn = new JButton("Button");
int value = JOptionPane.showOptionDialog(this,
                    new Object[]{txt, btn},
                    "Hello World",
                    JOptionPane.OK_CANCEL_OPTION, 
                    JOptionPane.INFORMATION_MESSAGE,
                    null, null, null);

But TextBox & Button showing vertically. How can I show them in horizontally ? Please help... Thanks.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Temp Expt
  • 61
  • 1
  • 4
  • 11

1 Answers1

4

From here you can actually do it like this, setting an JPanel which has a textfield and a button.

int value = JOptionPane.showOptionDialog(this,
                    getPanel(),
                    "Hello World",
                    JOptionPane.OK_CANCEL_OPTION, 
                    JOptionPane.INFORMATION_MESSAGE,
                    null, null, null);

private JPanel getPanel() {
    JPanel panel = new JPanel();
    JTextField txt = new JTextField(20);
    JButton btn = new JButton("Button");

    panel.add(txt);
    panel.add(btn);

    return panel;
}

EDIT Each JPanel object is initialized to use a FlowLayout, unless you specify differently when creating the JPanel. as per the doc here.

Community
  • 1
  • 1
Vinay
  • 6,891
  • 4
  • 32
  • 50
  • @JJPA It's working fine. I'm marking this as answered. Thanks a lot. One more question please: How to add items in jPanel vertically ? panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); I'm using this, but not working. Thanks in advance. – Temp Expt Aug 27 '13 at 11:14
  • @TempExpt try with `new BoxLayout(panel, BoxLayout.PAGE_AXIS)` as per the docit alligns components top to bottom I would make use of `new GridLayout(0,1)` instead. Try with that once. But the space will be divided equally. – Vinay Aug 27 '13 at 13:14