【问题标题】:How to enable a disabled JRadioButton如何启用禁用的 JRadioButton
【发布时间】:2012-12-18 05:06:53
【问题描述】:

我有两个 JRadioButton,每个都有 ImageIcon。由于我正在使用 ImageIcons,我需要给出一个按钮被选中而另一个按钮未被选中的外观。为此,我尝试禁用另一个按钮,该按钮会自动将 ImageIcon 更改为禁用外观。

问题是当我点击禁用的 JRadioButton 时,什么也没有发生,甚至 JRadioButton 上的 ActionListener 都没有被调用。

有没有办法通过直接点击禁用的 JRadioButton 来启用它?一旦它被禁用,它的 ActionListener 就不再被调用,所以我无法通过点击它来启用它。

基本上,我试图使用 ImageIcons 显示当一个被选中时,另一个未被选中。

//Below part of my code how I initialize the buttons
ButtonGroup codeSearchGroup = new ButtonGroup();

searchAllDocs = new JRadioButton(new ImageIcon(img1));
searchCurrDoc = new JRadioButton(new ImageIcon(img2));

RadioListener myListener = new RadioListener();
searchAllDocs.addActionListener(myListener);
searchCurrDoc.addActionListener(myListener);

codeSearchGroup.add(searchAllDocs);
codeSearchGroup.add(searchCurrDoc);


//Below listener class for buttons
class RadioListener implements ActionListener {  
    public void actionPerformed(ActionEvent e) {

        if(e.getSource() == searchAllDocs){
            searchAllDocs.setEnabled(true);
            System.out.println("Search All documents pressed. Disabling current button...");
            searchCurrDoc.setEnabled(false);

        } 
        else{
            searchCurrDoc.setEnabled(true);
            System.out.println("Search Current document pressed. Disabling all button...");
            searchAllDocs.setEnabled(false);
        }
    }


}

提前致谢。

【问题讨论】:

    标签: java swing jradiobutton


    【解决方案1】:

    ActionListener 在禁用模式下不会触发,但鼠标事件会。

    因此只需将MouseAdapter 添加到JRadioButton 并覆盖mouseClicked(..) 并在覆盖的方法中调用setEnable(true),如下所示:

        JRadioButton jrb = new JRadioButton("hello");
        jrb.setEnabled(false);
    
        jrb.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent me) {
                super.mouseClicked(me);
                JRadioButton jrb = (JRadioButton) me.getSource();
                if (!jrb.isEnabled()) {//the JRadioButton is disabled so we should enable it
                    //System.out.println("here");
                    jrb.setEnabled(true);
                }
            }
        });
    

    虽然我必须说有一些歪曲的逻辑在起作用。如果某些东西被禁用是有原因的,那么我们不应该让用户能够启用。如果我们这样做,应该有一个控制系统,我们可以选择启用/禁用按钮,它不会成为控制系统本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多