单选按钮上的动作侦听器

aga*_*wav 9 java applet swing actionlistener jradiobutton

我想根据选择的单选按钮设置文本框的可编辑选项?如何在单选按钮上编写动作侦听器?

zal*_*314 6

我的Java有点生疏,但这应该是你想要的.

这是你的倾听者:

private RadioListener implements ActionListener{

    private JTextField textField;

    public RadioListener(JTextField textField){
        this.textField = textField;
    }

    public void actionPerformed(ActionEvent e){
        JRadioButton button = (JRadioButton) e.getSource();

        // Set enabled based on button text (you can use whatever text you prefer)
        if (button.getText().equals("Enable")){
            textField.setEditable(true);
        }else{
            textField.setEditable(false);
        }
    }
}  
Run Code Online (Sandbox Code Playgroud)

以下是设置它的代码.

JRadioButton enableButton = new JRadioButton("Enable");
JRadioButton disableButton = new JRadioButton("Disable");

JTextField field = new JTextField();

RadioListener listener = new RadioListener(field);

enableButton.addActionListener(listener);
disableButton.addActionListener(listener);
Run Code Online (Sandbox Code Playgroud)


pbi*_*ble 6

这是我在这种情况下使用的解决方案.

    //The text field
    JTextField textField = new JTextField();

    //The buttons
    JRadioButton rdbtnAllowEdit = new JRadioButton();
    JRadioButton rdbtnDisallowEdit = new JRadioButton();

    //The Group, make sure only one button is selected at a time in the group
    ButtonGroup editableGroup = new ButtonGroup();
    editableGroup.add(rdbtnAllowEdit);
    editableGroup.add(rdbtnDisallowEdit);

    //add allow listener
    rdbtnAllowEdit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            textField.setEditable(true);

        }
    });

    //add disallow listener
    rdbtnDisallowEdit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            textField.setEditable(false);

        }
    });
Run Code Online (Sandbox Code Playgroud)


GET*_*Tah 2

尝试这个:

JRadioButton myRadioButton = new JRadioButton("");
myRadioButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
      // Do something here...
    }
});
Run Code Online (Sandbox Code Playgroud)