I want to make JTextField
part of JRadioButton
or hook them together.
my intention is to let the user fill in the text field when he selects the radio button. For this reason I have created custom radio button which extends from JradioButton
. I should be able to add it to buttonGroup
ButtonGroup buttonGroup = new ButtonGroup()
RadioButtonWithTextField radio1 = RadioButtonWithTextField("only to");
RadioButtonWithTextField radio2 = RadioButtonWithTextField("not only to");
buttonGroup.add(radio1 );
buttonGroup.add(radio1 );
radio1.setSelected(true);
The problem is, my TextField does not adjust it's size according to what I type in it or setText to it programmatically.
If I change the text of radio button after displaying the component it does not show all part of it.
Does anyone know or have experience in custom component creation?
public class RadioButtonWithTextField extends JRadioButton {
private JTextField textField;
public RadioButtonWithTextField(String text) {
super(text);
createComponents();
layoutComponents();
}
private void createComponents() {
textField = new WebTextField("",30);
textField.setPreferredSize(new Dimension(60,20));
}
private void layoutComponents() {
setLayout(new FlowLayout(FlowLayout.TRAILING,2,2));
add(textField);
}
public WebTextField getTextField() {
return textField;
}
public void setTextField(WebTextField textField) {
this.textField = textField;
}
}
I would follow @MadProgrammer's suggestion to create a JPanel class that consists of a JRadioButton and a JTextField. The below works for me.
public class RadioButtonPanel extends JPanel {
JRadioButton jRadioButton;
JTextField jTextField;
RadioButtonPanel(String radioButtonName) {
jRadioButton = new JRadioButton(radioButtonName);
jTextField = new JTextField(10);
this.setLayout(new FlowLayout());
this.add(jRadioButton);
this.add(jTextField);
jRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
handleEvent();
}
});
}
private void handleEvent() {
System.out.println(jRadioButton.getText() + " is selected, the customized text is " + jTextField.getText());
}
public static void main(String[] args) {
JFrame jFrame = new JFrame();
RadioButtonPanel radioButtonPanel1 = new RadioButtonPanel("Apple");
RadioButtonPanel radioButtonPanel2 = new RadioButtonPanel("Banana");
RadioButtonPanel radioButtonPanel3 = new RadioButtonPanel("Pear");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButtonPanel1.jRadioButton);
buttonGroup.add(radioButtonPanel2.jRadioButton);
buttonGroup.add(radioButtonPanel3.jRadioButton);
jFrame.setLayout(new GridLayout(3, 1, 5, 5));
jFrame.add(radioButtonPanel1);
jFrame.add(radioButtonPanel2);
jFrame.add(radioButtonPanel3);
jFrame.pack();
jFrame.setVisible(true);
}
}
A sample UI would be: