[英]How to select a JRadioButton from ButtonGroup?
我嘗試在java中創建一個圖像創建程序(使用正方形/圓形/等)我在ButtonGroup中有一些JRadioButtons,它們象征着我的程序的“模式”(如果我畫一個圓圈,其他東西/如果我移動對象)。 當我點擊不同模式時,“模式”會發生變化,我可以按照自己的意願行事。 我的問題是當我嘗試通過雙擊對象來更改模式。 我是在MouseListener中完成的。 我可以選擇對象,更改“模式”,但我無法更改ButtonGroup上選定的JRadio按鈕。 我搜索了一會兒(因為setSelected()不起作用)。 我知道ButtonGroup只能一次選擇一個按鈕。 我怎樣才能取消選擇一個並選擇我需要的那個(第一個)。 謝謝你的任何建議。
來自文檔:
public void setSelected(boolean b)
設置按鈕的狀態。 請注意,此方法不會觸發actionEvent。 調用doClick以執行程序操作更改。
如上所述,使用:
radioBtn.doClick();
我創建了一個小方法,允許我設置任何單選按鈕組。 如果您不想使用if用於任何單選按鈕,則非常方便。
public void setButtonGroup(int rdValue, Enumeration elements ){
while (elements.hasMoreElements()){
AbstractButton button = (AbstractButton)elements.nextElement();
if(Integer.parseInt(button.getActionCommand())==rdValue){
button.setSelected(true);
}
}
}
然后
setButtonGroup(yourValue, yourButtonGroup.getElements());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.