【问题标题】:How to consume JRadioButton select on mouse click doesn't seem to work如何在鼠标单击时使用 JRadioButton 选择似乎不起作用
【发布时间】:2013-08-07 13:54:49
【问题描述】:

我正在创建一个非常简单的类来覆盖 Swing JRadioButton,它允许用户设置一个字段来确定单选按钮是否可选。

public class SelectableRadio extends JRadioButton implements MouseListener
private boolean selectable = true;
public SelectableRadio()
{
    super();
    addMouseListener(this);
}

public void setSelectable(boolean select)
{
    selectable = select;
}

@Override
public void mousePressed(MouseEvent e)
{
    if (!selectable)
    {
        e.consume();
    }
}

所有其他方法都已实现。这不起作用。当 SelectableRadio 按钮设置为不可选择时,单选按钮在单击时仍处于选中状态。

有什么帮助吗?

【问题讨论】:

  • 你为什么要迷惑你的用户?
  • 如果无法选择,每次拨打setSelection(false)即可。
  • 或者,为了避免混淆您的用户,正如 kleopatra 所说,直接禁用该按钮。
  • 我只是想构建一个单选按钮,它没有变灰并且在组中不可选择。

标签: java swing jradiobutton mouse-listeners buttongroup


【解决方案1】:

您需要更改您的 setSelectable 代码,并添加以下内容:

if (editable) {
    this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    super.enableEvents(Event.MOUSE_DOWN | Event.MOUSE_UP);
} else {
    this.setCursor(CursorFactory.createUnavailableCursor());
    super.disableEvents(Event.MOUSE_DOWN | Event.MOUSE_UP);
}

【讨论】:

  • 这实际上就是我想要的。感谢您回答我的问题。
【解决方案2】:

您通常将JRadioButtons 放入ButtonGroup

这是来自Oracle tutorial 的示例。

//Create the radio buttons.
JRadioButton birdButton = new JRadioButton(birdString);
birdButton.setMnemonic(KeyEvent.VK_B);
birdButton.setActionCommand(birdString);
birdButton.setSelected(true);

JRadioButton catButton = new JRadioButton(catString);
catButton.setMnemonic(KeyEvent.VK_C);
catButton.setActionCommand(catString);

JRadioButton dogButton = new JRadioButton(dogString);
dogButton.setMnemonic(KeyEvent.VK_D);
dogButton.setActionCommand(dogString);

JRadioButton rabbitButton = new JRadioButton(rabbitString);
rabbitButton.setMnemonic(KeyEvent.VK_R);
rabbitButton.setActionCommand(rabbitString);

JRadioButton pigButton = new JRadioButton(pigString);
pigButton.setMnemonic(KeyEvent.VK_P);
pigButton.setActionCommand(pigString);

//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);
group.add(dogButton);
group.add(rabbitButton);
group.add(pigButton);

//Register a listener for the radio buttons.
birdButton.addActionListener(this);
catButton.addActionListener(this);
dogButton.addActionListener(this);
rabbitButton.addActionListener(this);
pigButton.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
    picture.setIcon(new ImageIcon("images/" 
                              + e.getActionCommand() 
                              + ".gif"));
}

【讨论】:

    【解决方案3】:

    你试过 jRadioButton 的 enabled 属性吗?它使其可选择或不可选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 2022-12-11
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      相关资源
      最近更新 更多