Toggle a component's 'enable' property according to a radio button in netbeans

风格不统一 提交于 2019-12-31 07:13:25

问题


I have two radio buttons in a button group and in the same panel I have a text box and a button. I want to enable the text box and the button only when the second button is selected and be disabled when the other radio button is selected. I've tried this and it didn't work.

private void radio_button2ActionPerformed(java.awt.event.ActionEvent evt) {
if(buttonGroup1.getSelection()==radio_button2)
{
    button.setEnabled(true);
    textbox.setEnabled(true);
}

Where have I gone wrong?


回答1:


You don't want to use an ActionListener because the event only fires when you click the button. Instead you can use an ItemListener so an event is generated when the item is selected or deselected (by clicking the other radio button). Something like:

radioButton2.addItemListener( new ItemListener()
{
    public void itemStateChanged(ItemEvent e)
    {
        JRadioButton button = (JRadioButton)e.getSource();
        component1.setEnabled( button.isSelected() );
        component2.setEnabled( button.isSelected() );
    }
});


来源:https://stackoverflow.com/questions/6444791/toggle-a-components-enable-property-according-to-a-radio-button-in-netbeans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!