我应该假设我有一个GUI程序,用户最多可以选择他们想要购买的三件物品,然后选择一种运输速度。用户然后点击“购买”按钮。我的程序应该输出一个简要说明,例如: 您在购买这些物品在定期航运:项目1 ITEM2项目3 您在快速送货购买这些物品:ITEM2项目3为什么每次点击后我的GUI程序都会显示输出?
我需要帮助搞清楚如何防止我的程序从输出任何东西直到最后。
我刚接触到这些概念,所以请给我建议和例子!
这里是我的代码:
我应该假设我有一个GUI程序,用户最多可以选择他们想要购买的三件物品,然后选择一种运输速度。用户然后点击“购买”按钮。我的程序应该输出一个简要说明,例如: 您在购买这些物品在定期航运:项目1 ITEM2项目3 您在快速送货购买这些物品:ITEM2项目3为什么每次点击后我的GUI程序都会显示输出?
我需要帮助搞清楚如何防止我的程序从输出任何东西直到最后。
我刚接触到这些概念,所以请给我建议和例子!
这里是我的代码:
这是因为您使用的是每个按钮的点击相同的代码,而不是检查哪个按钮被点击。另外,我在代码中看不到购买按钮?我假设你的意思是单选按钮,但你应该使用JButton
与单选按钮相结合。
来解决,这将是让你的主类实现ActionListener
而不是不同类的,像这样的一种方式:
public class OnlineShopping extends JFrame implements ActionListener {
//Variable declarations
private JButton purchaseButton;
public OnlineShopping() {
//Create various elements
purchaseButton = new JButton("Purchase");
mainPanel.add(purchaseButton);
purchaseButton.addActionListener(this); //Add the JFrame as a listener
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == purchaseButton) {
if (regularShippingSpeedRadioButton.isSelected()) {
//User has chosen to purchase at regular shipping
} else if (fastShippingSpeedRadioButton.isSelected()) {
//User has chosen to purchase at fast shipping
}
}
}
}
我想那是因为你没有覆盖run方法之前只需要输入@覆盖运行mehod –
@ user7790438你好!感谢您的建议:)我也这么认为,但每次点击后它仍然会显示输出:/ – cossii
错误,为什么您首先将该监听器添加到所有按钮? – GhostCat