Search code examples
javaswingjtextfieldjradiobutton

How do I combine a JTextField and a JRadioButton?


I would like to have a JRadioPanel with three options. The first two are hardcoded options, and I want the third to be an 'Other' button. I would like to have a JTextField instead of text as the title of that button, but I'm not sure how to do that. I tried simply putting the field as the argument for the radio button, but it didn't like that much. I haven't found anything online to tell me how, except maybe through NetBeans, and that doesn't do me much good. Is there any way to easily do this, or will I have to do some fancy stuff with the layout?

Okay, new problem. The buttons are all looking right, but for some reason they're in a row instead of in a column. Here's the code for it. Not sure why it's doing this.

    tf2 = new JTextField("Other", 20);
    newName.setActionCommand("newname");
    fulfillment.setActionCommand("fulfillment");
    fulfillment.setSelected(true);
    type.add(fulfillment);
    type.add(newName);
    fulfillment.addActionListener(this);
    newName.addActionListener(this);
    GridBagConstraints rC = new GridBagConstraints();
    JPanel radioPanel3 = new JPanel(new GridBagLayout());
    rC.gridwidth = 2;
    radioPanel3.add(fulfillment);
    rC.gridy = 1;
    radioPanel3.add(newName);
    rC.gridy = 2;
    rC.gridwidth = 1;
    radioPanel3.add(other);
    rC.gridx = 1;
    radioPanel3.add(tf2);
    c.gridx = 10;
    c.gridy = 4;
    pane.add(radioPanel3, c);

Solution

  • Place the third radiobutton without text and add JTextField. E.g. Use GridBagLayout where the first and the second radiobuttons take 2 columns and in the third row the "empty" radiobutton has row=2 col=0 and JTextField row=2 col=1