2017-04-12 58 views
0

我應該假設我有一個GUI程序,用戶最多可以選擇他們想要購買的三件物品,然後選擇一種運輸速度。用戶然後點擊「購買」按鈕。我的程序應該輸出一個簡要說明,例如: 您在購買這些物品在定期航運:項目1 ITEM2項目3 您在快速送貨購買這些物品:ITEM2項目3爲什麼每次點擊後我的GUI程序都會顯示輸出?

我需要幫助搞清楚如何防止我的程序從輸出任何東西直到最後。

我剛接觸到這些概念,所以請給我建議和例子!

這裏是我的代碼:

+0

我想那是因爲你沒有覆蓋run方法之前只需要輸入@覆蓋運行mehod –

+0

@ user7790438你好!感謝您的建議:)我也這麼認爲,但每次點擊後它仍然會顯示輸出:/ – cossii

+0

錯誤,爲什麼您首先將該監聽器添加到所有按鈕? – GhostCat

回答

1

這是因爲您使用的是每個按鈕的點擊相同的代碼,而不是檢查哪個按鈕被點擊。另外,我在代碼中看不到購買按鈕?我假設你的意思是單選按鈕,但你應該使用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 
      } 
     } 
    } 
} 
+0

這會在不同的班級嗎? – cossii

+0

這些都包含在你的'OnlineShopping'類中。 – MarkSill

+0

謝謝!我編輯了我的程序,按鈕工作正常:)我只是想知道,爲每個項目選擇有單獨的單選按鈕是否有意義? – cossii

相關問題