Java GUI JButton,如何将按钮(即问题)分配给答案
好的,我只需要一个简单的答案/提示/建议,或者如果你们对修复我的JavaGUI代码感到慷慨的话 所以基本上我的问题是,在这个游戏中,当用户回答我的一个问题时,他/她可以得到正确的答案,但是,有一个主要的缺陷,用户可以使用我的任何问题的任何答案来得到正确的答案 我是这样做的,但我不知道怎么做其他任何方式!我对此做了一些研究,但在谷歌上找不到任何东西,因为我甚至不知道如何表达这个问题,所以我来到这样一个论坛,希望得到一些提示或答案 不,我不希望任何人改变任何事情,只是寻找一些答案来理解该怎么做 代码:Java GUI JButton,如何将按钮(即问题)分配给答案,java,swing,user-interface,jbutton,Java,Swing,User Interface,Jbutton,好的,我只需要一个简单的答案/提示/建议,或者如果你们对修复我的JavaGUI代码感到慷慨的话 所以基本上我的问题是,在这个游戏中,当用户回答我的一个问题时,他/她可以得到正确的答案,但是,有一个主要的缺陷,用户可以使用我的任何问题的任何答案来得到正确的答案 我是这样做的,但我不知道怎么做其他任何方式!我对此做了一些研究,但在谷歌上找不到任何东西,因为我甚至不知道如何表达这个问题,所以我来到这样一个论坛,希望得到一些提示或答案 不,我不希望任何人改变任何事情,只是寻找一些答案来理解该怎么做 代码
答案需要与问题联系起来(听起来很明显) 您可以做的是将答案和问题保存在某种类型的
地图中
,这将允许您根据哪个问题处于活动状态来循环回答
private Map<String, String> mapQA;
private String currentQuestion;
//...
mapQA = new HashMap<>(4);
mapQA.put(q1, a1); // Or how ever you want to do it...
//...
if (command.equals("Question 1, 100 points"))
{
//set the text to blank
btn1.setText("");
//set the label with the question
lblInfo.setText(q1);
currentQuestion = q1;
}
//if this button is clicked...
else if (command.equals("Question 2, 200 points"))
//...
if (command.equals("Check answer"))
{
//the textfield is equal to the variable input
input = txtInput.getText();
String answer = mapQA.get(currentQuestion);
if (answer.equals(txtInput.getText()) {...
这样,你可以简单地使用
JButton btn = (JButton)event.getSource();
//set the text to blank
btn .setText("");
//set the label with the question
currentQuestion = mapButtons.get(btn)
lblInfo.setText(currentQuestion);
取消
if
语句,除了“检查答案”按钮;) 由于这是一个GUI问题,您可能应该包括一些正在发生的事情和您想要发生的事情的屏幕截图-文本描述并不能准确地给出您想要做什么的清晰图片。我们不能亲自测试,因为你没有给我们一个答案(你应该一直这样做)。你问题的英语部分没有告诉我们你面临的任何问题。请阅读
Map<JButton, String> mapButtons;
//...
btn1 = new JButton ("Question 1, 100 points");
//...
mapButtons = new HashMap<JButton, String>(4);
mapButtons.put(btn1, "..."); // Question 1...
JButton btn = (JButton)event.getSource();
//set the text to blank
btn .setText("");
//set the label with the question
currentQuestion = mapButtons.get(btn)
lblInfo.setText(currentQuestion);