繁体   English   中英

如何使用JRadioButton select鼠标单击似乎不起作用

[英]How to consume JRadioButton select on mouse click doesn't seem to work

我正在创建一个非常简单的类来覆盖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按钮设置为NOT selectable时,单击时仍会选择单选按钮。

有什么帮助吗?

您需要更改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);
}

通常,您将JRadioButton放入ButtonGroup

这是Oracle教程中的示例。

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

您是否尝试过jRadioButton的enabled属性? 它使它成为可选择的或不可选择的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM