2013-03-05 64 views
-1

У меня есть простая система заказа, которая требует от пользователя ввода имени, имени клиента и пароля. После того, как пользователь завершит этот процесс, он отобразит поле со списком, в котором будут разные блюда.не работает должным образом

Что я хочу, так это то, что как только я нажал на еду, он должен отобразить название выбранной мной еды и выполнить действие, которое я объявил в actionlistener.

Программа компилируется отлично, но логика, которую я хочу, не работает, я стараюсь исправить это, но я думаю, что не могу сделать это самостоятельно, пожалуйста, помогите мне спасибо!

import java.util.Scanner; 
    import javax.swing.*; 
    import java.awt.*; 
    import java.awt.event.*; 


public class SubokUlit { 
    private JComboBox combo; 
    private String a = ""; 
    private static int answer; 
    private static int total = 0; 
    private static int total1 = 0; 
    private static int wew = 0; 
    private static String order1 = ""; 
    private static String order2 = ""; 
    private static Scanner inp = new Scanner(System.in); 


public SubokUlit(){ 
    String mgaPagkainTo[] = {"PM1 (Paa/ Spicy Paa with Thigh part)","PM2 (Pecho)"};  
    JFrame frame = new JFrame("Mang Inasal Ordering System"); 
    JPanel panel = new JPanel(); 
    combo = new JComboBox(mgaPagkainTo); 
    combo.setBackground(Color.gray); 
    combo.setForeground(Color.red); 
    panel.add(combo); 
    frame.add(panel); 
     combo.addActionListener(new ActionListener(){ // The logic in here does not work 
    public void actionPerformed(ActionEvent e){ 
     String str = (String)combo.getSelectedItem(); 
     a = str; 
     if(a.equals("PM1 (Paa/ Spicy Paa with Thigh part)")){ // If I select PM1 in the combo box it should do the following. But it doesn't work 
       System.out.print ("\n\n\n\t\tYou have chosen Paborito Meal 1.\n"); 
        System.out.print ("\t\t\tPlease enter the quantity: "); 
        int quantity1 = inp.nextInt(); 
        total = quantity1 * 99; 
        order1 = quantity1 + " " + "PM1 " + "         " + total +"\n"; 
     } 
     else if(a.equals("PM2 (Pecho)")){ // The same thing should alaso happen here in PM2 
      System.out.print ("\n\n\n\t\tYou have chosen Paborito Meal 2.\n"); 
       System.out.print ("\t\t\tPlease enter the quantity: "); 
       int quantity2 = inp.nextInt(); 
       total1 = quantity2 * 99; 
       order2 = quantity2 + " " + "PM2 " + "         " + total1 +"\n"; 
     } 
    } 
    }); 

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(300,100); 
     frame.setVisible(true); 
} 


public static void main(String[]args) { 
     Scanner inp = new Scanner(System.in); 
     String userNamePoe = ""; 
     String customerNamePoe = ""; 
     String sanKaKain = ""; 
     boolean ulitinMoPows = true; 
     boolean tryAgain = true; 

     System.out.print("\nInput Customer Name: "); 
     String customerName = inp.nextLine(); 
     customerNamePoe = customerName; 
     System.out.print("\nInput Cashier Name: "); 
     String user = inp.nextLine(); 
     userNamePoe = user; 
    do{ 
     System.out.print("\nInput either Dine In or Take Out: "); 
     String dInDOut = inp.nextLine(); 
     sanKaKain = dInDOut; 
      if (sanKaKain.equals("Dine In") || sanKaKain.equals("Take Out")){ 
      System.out.print(""); 
      ulitinMoPows = false; 
      } 
      else{ 
      JOptionPane.showMessageDialog(null, "Try again! Please input Dine In or Take Out only!","Error", JOptionPane.ERROR_MESSAGE); 
       ulitinMoPows = true; 
       System.out.print ("\f"); 
       } 
    }while(ulitinMoPows); 
    do{ 
     System.out.print("\nInput password: "); 
     String pass = inp.nextLine(); 
     if(pass.equals("admin")){ 
      System.out.print(""); 
      tryAgain = false; 
     } 
     if(!pass.equals("admin")){ 
      JOptionPane.showMessageDialog(null, "Try again! Invalid password!","Error Logging-In", JOptionPane.ERROR_MESSAGE); 
     tryAgain = true; 
     System.out.print ("\f"); 
     } 
}while(tryAgain); 

     System.out.print("\n\n\t\tCashier: " +userNamePoe); 
     System.out.print("       "+sanKaKain); 
     System.out.print("\n\t\tCustomer Name: " +customerNamePoe); 

     SubokUlit j = new SubokUlit(); //Supposedly, once the selecting of meal is done, it should now go to the next part wherein the total bill will display and asks the user how much is his cash. 


    int lahatNgOrderMo = total + total1; 
    double multiplierVat = 0.12; 
    double vatCollected = lahatNgOrderMo * multiplierVat; 
     System.out.print("\n\n\tYour total bill is: "+lahatNgOrderMo); // Displays the bill 
     System.out.print("\n\tCash Tendered: "); // Asks the user how much is his cash 
    double cashTendered = inp.nextInt(); 
    double sukliMo = cashTendered - lahatNgOrderMo; 


     System.out.print("\n\n\t\t       MANG INASAL"); 
     System.out.print("\n\t\t      BLUMENTRITT BRANCH"); 
     System.out.print("\n\t\t   #1631-1633 BLUMENTRITT ST.,"); 
     System.out.print("\n\t\t   STA CRUZ. MANILA 0000"); 
     System.out.print("\n\t\t    (932) 885-5844\n"); 
     System.out.print("\n\t\t   Operated by: R L YU"); 
     System.out.print("\n\t\t   TIN 202-161-017-000 VAT"); 
     System.out.print("\n\t\t  ACC. NO.: 050-204079836-000019"); 
     System.out.print("\n\t\t    Tel. #: (02)493-6801"); 
     System.out.print("\n\n\t\tCashier: " +userNamePoe); 
     System.out.print("\t\t STATION: 2"); 
     System.out.print("\n\t\t---------------------------------------------"); 
     System.out.print("\n\t\tO.R #: 84486"); 
     System.out.print("       "+sanKaKain); 
     System.out.print("\t\t\n    Customer Name: " +customerNamePoe); 
     System.out.print("      24"); 
     System.out.print("\n\t\t---------------------------------------------"); 
     System.out.print("\n\t\t     >>SETTLED<<\n\n"); 
     System.out.print(""+order1); 
     System.out.print(""+order2); 
     System.out.print("\n\n\t\tSUB TOTAL:        "+lahatNgOrderMo); 
     System.out.print("\n\t\tDELIVERY VAT:       0.00"); 
     System.out.print("\n\t\t          ======"); 
     System.out.print("\n\t\tAMOUNT DUE:        "+lahatNgOrderMo); 
     System.out.print("\n\n\t\tVAT 12% COLLECTED     "+vatCollected); 
     System.out.print("\n\n\t\tCASH Tendered:       "+cashTendered); 
     System.out.print("\n\t\t          ======"); 
     System.out.print("\n\t\tCHANGE:         "+sukliMo); 
     System.out.print("\n\t\t    >>Ticket #: 62<<"); 
     System.out.print("\n\t\t  Created: "); 
     System.out.print("\n\t\t  SETTLED: "); 
     System.out.print("\n\n\t\t*********************************************"); 
     System.out.print("\n\t\tTHIS SERVES AS AN OFFICIAL RECEIPT."); 
     System.out.print("\n\n\t\tFor Feedback: TEXT MIO467(Comments/ Suggest"); 
     System.out.print("\n\t\tions) and SEND to 0917-5941111 or CALL US"); 
     System.out.print("\n\t\tat 0917-5596258"); 
     System.out.print("\n\t\tEmail: [email protected]"); 
     System.out.print("\n\n\t\t  THANK YOU FOR DINING WITH US!"); 
     System.out.print("\n\n\t\t*********************************************"); 
     System.out.print("\n\t\tS/N: 120416ASL03/1105-6105-9230"); 
     System.out.print("\n\t\tDT S/N: 41-L6971 (P0S1)"); 
     System.out.print("\n\t\tPERMIT NO: 0412-031-125295-000"); 
     System.out.print("\n\t\tMIN: 120276752"); 


} 
} 
+2

, где проблема? Что это такое? Что вы пробовали? где вы застряли? Ответ на любой из этих вопросов может помочь нам. – phadaphunk

+0

@PhaDaPhunk логика в actionListener не работает. Каждый раз, когда я нажимаю еду в поле со списком, он не выполняет действия, которые я объявил –

+0

@ Ангел Кази Монтойя. Я отредактировал свой ответ. Можете ли вы попробовать ввести код? – Joetjah

ответ

1

Вы должны убедиться, что EventListener прилагается к вашему JComboBox, так что приложение знает, что делать, когда что-то происходит.

В этом случае вы хотите прикрепить ItemListener().

Вы можете использовать что-то вроде этого:

combo.addItemListener(new ItemListener() { 

    @Override 
    public void itemStateChanged(ItemEvent e) { 
     System.out.println("Meal chosen: " + combo.getSelectedItem().toString()); 
     String optionalParameter = combo.getSelectedItem().toString(); 
     DoMethodWhatYouNeedToDoWhenYouSelectedSomething(optionalParameter); 
    } 
}); 

EDIT: Ваш код должен выглядеть так:

combo.addActionListener(new ItemListener(){ 

    @Override 
    public void itemStateChanged(ItemEvent e){ 
     String str = (String)combo.getSelectedItem(); 
     a = str; 
     if(a.equals("PM1 (Paa/ Spicy Paa with Thigh part)")){ 
      System.out.print ("\n\n\n\t\tYou have chosen Paborito Meal 1.\n"); 
      System.out.print ("\t\t\tPlease enter the quantity: "); 
      int quantity1 = inp.nextInt(); 
      total = quantity1 * 99; 
      order1 = quantity1 + " " + "PM1 " + "         " + total +"\n"; 
     } 
     else if(a.equals("PM2 (Pecho)")){ 
      System.out.print ("\n\n\n\t\tYou have chosen Paborito Meal 2.\n"); 
      System.out.print ("\t\t\tPlease enter the quantity: "); 
      int quantity2 = inp.nextInt(); 
      total1 = quantity2 * 99; 
      order2 = quantity2 + " " + "PM2 " + "         " + total1 +"\n"; 
     } 
    } 
}); 
+0

Вы хотите сказать, что мне нужно переключиться на ItemListener вместо actionListener? Проверьте мой код выше –

+0

Да и переименуйте 'actionPerformed' в' itemStateChanged'. Проверьте мое редактирование :) – Joetjah

+0

Сэр говорит, что не является абстрактным и не отменяет метод abstarct. Что мне делать? –

Смежные вопросы