2016-12-07 48 views
0
JButton btnNewButton = new JButton("Pepsi"); 
    btnNewButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      changeD(); 
     } 
    }); 
    btnNewButton.setBounds(23, 11, 80, 29); 
    contentPane.add(btnNewButton); 
    JButton btnNewButton_1 = new JButton("Sprite"); 
    btnNewButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      changeD(); 
     } 
    }); 
    btnNewButton_1.setBounds(113, 11, 80, 29); 
    contentPane.add(btnNewButton_1); 
    JButton btnFanta = new JButton("Fanta"); 
    btnNewButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      changeD(); 
     } 

    }); 

這些都是調用method.This的按鈕是我有一個問題,只有一個按鈕點擊作品,百事按鈕試圖致電多個按鈕的一種方法,但只有一個按鈕使用方法

接下來的部分是我打來的方法。它確定輸入的硬幣和金額是否正確。你有一個錯誤

public double changeD() { 

     JOptionPane.showMessageDialog(null, "This Product costs 1.50 EU"); 
     String payment = JOptionPane.showInputDialog(null, "Please insert cash"); 
     int intAmount = Integer.parseInt(payment); 
     double drinkPrice = 1.50; 
     double changeDue = intAmount - drinkPrice; 
     if (intAmount == 2 + 1 + .50 && intAmount > drinkPrice) 

     { 
      JOptionPane.showInputDialog(null, "Please take your product and change " + changeDue); 

     } 

     else if (intAmount != 2 + 1 + .50 || intAmount < drinkPrice) 

     { 
      JOptionPane.showMessageDialog(null, "Please insert correct amount or coins "); 
     } 

     return (Double) null; 
+1

嘗試'btnNewButton_1.addActionListener'和'btnFanta.addActionListener'。你繼續添加動作偵聽器到同一個按鈕。 –

+0

你在暗示我改變了什麼? –

+0

對不起,我看不到整個評論,謝謝你和我現在將改變它:) –

回答

0

通知可能做複製粘貼您設置相同的按鈕用的ActionListener兩次

JButton btnNewButton = new JButton("Pepsi"); 
btnNewButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     changeD(); 
    } 
}); 
btnNewButton.setBounds(23, 11, 80, 29); 
contentPane.add(btnNewButton); 
JButton btnNewButton_1 = new JButton("Sprite"); 

//Wrong button here !!!!!!!!!!!!!!!!!!! Should be btnNewButton_1 
btnNewButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     changeD(); 
    } 
}); 
btnNewButton_1.setBounds(113, 11, 80, 29); 
contentPane.add(btnNewButton_1); 
JButton btnFanta = new JButton("Fanta"); 
btnNewButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     changeD(); 
    } 

}); 
+0

請解釋問題和解決方案,不要只是轉儲代碼。除了別的,你已經在你的「答案」中留下了一個問題的實例。 –

+0

更好嗎? – urag

+0

我的問題是,我忽略了,我在每個地方引用相同的按鈕。程序在點擊任何按鈕時執行該方法。現在我只需要提供取消方法中購買的選項 –

相關問題