使用 JtextField 创建自定义 JRadioButton?

Creating custom JRadioButton with JtextField?

我想使 JTextField 成为 JRadioButton 的一部分或将它们连接在一起。 我的意图是让用户在选择单选按钮时填写文本字段。出于这个原因,我创建了从 JradioButton 扩展的自定义单选按钮。我应该可以将它添加到 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);

问题是,我的 TextField 不会根据我在其中键入的内容或以编程方式向其设置文本来调整其大小。

如果我在显示组件后更改单选按钮的文本,它不会显示所有部分。

有谁知道或有创建自定义组件的经验吗?

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;
    }

}

我会按照@MadProgrammer 的建议创建一个由 JRadioButton 和 JTextField 组成的 JPanel class。以下对我有用。

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);
}
}

样本 UI 将是: