英文:
ToggleGroup to toggle between male and female java
问题
我正在尝试创建一个切换按钮,用于更改所选的性别,我试图让它在男性和女性之间切换,但是当我运行它并选择一个组时,它既不选择男性也不选择女性。
ToggleGroup genderToggle = new ToggleGroup();
maleButton.setToggleGroup(genderToggle);
maleButton.setUserData("male");
femaleButton.setToggleGroup(genderToggle);
femaleButton.setUserData("female");
submitButton.setOnAction(new ButtonListener());
genderToggle.selectedToggleProperty().addListener(new ChangeListener<Toggle>()
{
public void changed(ObservableValue<? extends Toggle> ob, Toggle o, Toggle n)
{
RadioButton rb = (RadioButton)genderToggle.getSelectedToggle();
if (rb.getUserData().equals("male"))
{
maleButton.setSelected(true);
femaleButton.setSelected(false);
}
else if (rb.getUserData().equals("female"))
{
maleButton.setSelected(false);
femaleButton.setSelected(true);
}
else
{
maleButton.setSelected(false);
femaleButton.setSelected(false);
}
}
});
英文:
I am attempting to create a toggle button that changes the selected gender, I am trying to get it to toggle between male and female but when I run it and select a group, it doesn't select either one.
ToggleGroup genderToggle = new ToggleGroup();
maleButton.setToggleGroup(genderToggle);
maleButton.setUserData("male");
femaleButton.setToggleGroup(genderToggle);
femaleButton.setUserData("female");
submitButton.setOnAction(new ButtonListener());
genderToggle.selectedToggleProperty().addListener(new ChangeListener<Toggle>()
{
public void changed(ObservableValue<? extends Toggle> ob, Toggle o, Toggle n)
{
RadioButton rb = (RadioButton)genderToggle.getSelectedToggle();
if (genderToggle.equals("male"))
{
maleButton.setSelected(true);
femaleButton.setSelected(false);
}
else if (genderToggle.equals("female"))
{
maleButton.setSelected(false);
femaleButton.setSelected(true);
}
else
{
maleButton.setSelected(false);
femaleButton.setSelected(false);
}
}
});
答案1
得分: 1
我认为问题出在您在切换对象上使用了.equals(...)
,而应该首先获取用户数据字段,因为这是您设置为性别字符串的字段。例如:
if (genderToggle.getUserData().equals("female"))
{
maleButton.setSelected(false);
femaleButton.setSelected(true);
}
英文:
I think the issue is that you are using .equals(...)
on the toggle object, instead first get the user data field, as this is the one you set to the gender string. E.g.:
if (genderToggle.getUserData().equals("female"))
{
maleButton.setSelected(false);
femaleButton.setSelected(true);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论