2015-12-15 71 views
1

幫助!我不太瞭解java,但我試圖創建一個小程序,人們可以購買物品,並根據購買量更新庫存。我有兩個不同的類,但即時嘗試要做的是,我想獲得用戶從一個類購買的物品的數量,並使用該數字更新另一個類中的股票 - 這是我在其中的代碼段與在類之間調用特定方法

代碼掙扎採購項目

public class PurchaseItem extends JFrame implements ActionListener { 

JTextField ItemNo = new JTextField(5);          //Adds a text field named ItemNo 
JTextField AmountNo = new JTextField(5);         //Adds a text field named AmountNo 
TextArea information = new TextArea(6, 40);         //Adds a text area named Information 
TextArea reciept = new TextArea (10,50);         //Adds a text area named Reciept 
JButton Check = new JButton("Check");          //Adds a button named Check 
JButton Buy = new JButton("Buy");           //Adds a button named Buy 
DecimalFormat pounds = new DecimalFormat("£#,##0.00");      //For output to display in decimal and pounds format 




public PurchaseItem() {              //PurchaseItem class 

    this.setLayout(new BorderLayout());          //Adds a new layout for PurchaseItem 

    JPanel top = new JPanel();            //JPanel is a a container for other components 
    top.setLayout(new FlowLayout(FlowLayout.CENTER));      //It is set to the center of the frame 
    JPanel bottom = new JPanel();           //JPanel is a a container for other components 
    bottom.setLayout(new FlowLayout(FlowLayout.CENTER));     //It is set to the center of the frame 
    bottom.add(Buy);              //Insert the "Buy" JButton on the frame 
    this.add(bottom, BorderLayout.SOUTH);         //Button goes at the bottom of the frame 

    setBounds(100, 100, 450, 250);           //Sets the bounds of the frame 
    setTitle("Purchase Item");            //Sets the title of the frame 
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);      //Default option to exit frame is through button and not X sign 

    top.add(new JLabel("Enter Item Key:"));         //Add a new JLabel at the top of the frame 
    top.add(ItemNo);              //Set the ItemNo Text Field at the top of the frame 
    top.add(new JLabel ("Enter Amount:"));         //Add a new JLabel at the top of the frame 
    top.add(AmountNo);              //Set the AmountNo Text Field at the top of the frame 
    top.add(Check);               //Set the Check Button at the top of the frame 

    Buy.setText("Buy"); Buy.setVisible(true);        //Makes the text of the Buy Button visible 

    Check.addActionListener(this);           //Add an ActionListener to the Check Button 
    Buy.addActionListener(this);           //Add an ActionListener to the Buy Button 

    add("North", top); 
    JPanel middle = new JPanel();           //JPanel is a a container for other components 
    middle.add(information);            //Set the Information Text Area at the middle of the frame 
    add("Center", middle); 

    setResizable(false);             //Makes the frame not resizeable 
    setVisible(true);              //Makes the frame visible 
} 
@Override                 //Overrides the method of the PurchaseItem class to identify mistakes and typos  
public void actionPerformed(ActionEvent e) {        //actionPerformed class. This is called when the actionListener event happens 

    String ItemKey = ItemNo.getText();          //String for getting the user input from the ItemNo Text Field 
    String ItemAmount = AmountNo.getText();         //String for getting the user input from the AmountNo Text Field 
    String Name = StockData.getName(ItemKey);        //String for getting the name of the item from StockData 

    int Amount = Integer.parseInt(ItemAmount);        //Convert String ItemAmount into an Integer variable named Amount 

    int NewStock = StockData.getQuantity(ItemKey) - Amount;     //Integer named NewStock. NewStock is the current stock(from StockData) minus the Amount 

    double Total = Amount * StockData.getPrice(ItemKey);     //Double named Total. Total is the Amount multiplied by the price of the item(from StockData) 

    Calendar cal = Calendar.getInstance();         //Calendar named cal. getInstance is used to get the current time 

    SimpleDateFormat Date = new SimpleDateFormat("dd/MM/yyyy");    //SimpleDateFormat named Date. It is used to display the date 
    SimpleDateFormat Time = new SimpleDateFormat("HH:mm:ss");    //SimpleDateFormat named Time. It is used to display the time 


    if (Name == null){              //If the Name is invalid and has no return value 
     information.setText("There is no such item");      //Display the message on the Information Text Area 
    } 
    else if (Amount > StockData.getQuantity(ItemKey)) {      //Else if the Amount(User Input) is more than the quantity of the item(from StockData) 
    information.setText("Sorry there is not enough stock available");  //Display the message on the Information Text Area 
} 
    else {                 //Otherwise                
     information.setText(Name + " selected: " + Amount);    //Add the Name and the Amount of the item on the Information Text Area 
     information.append("\nIndividual Unit Price: " + pounds.format(StockData.getPrice(ItemKey))); //On a new line add the individual price of the item on the Information Text Area in a pound format(£) 
     information.append("\nCurrent Stock Available: " + StockData.getQuantity(ItemKey));    //On a new line add the current quantity available according to StockData on the Information Text Area 
     information.append("\nNew Stock After Sale: " + NewStock);          //On a new line add the NewStock on the Information Text Area 
     information.append("\n\nTotal: " + Amount + " Units" + " at " + pounds.format(StockData.getPrice(ItemKey)) + " each");  //On two new lines add the Amount plus the item price(from StockData). This becomes the Total 
     information.append("\n= " + pounds.format(Total));     //On a new line display the Total in a pounds format(£) on the Information Text Area 
    }   
    if (e.getSource() == Buy) {           //If the user clicks the Buy Button 
     int response = JOptionPane.showConfirmDialog(null, "Buy " + Amount + " Units" + " for " + pounds.format(Total) + "?");  //Show a confirm dialog asking the user to confirm the purchase with a Yes, No, or Cancel option 
     if (response == JOptionPane.YES_OPTION) {       //If the user clicks Yes on the confirm dialog 
     JFrame frame2 = new JFrame();          //Add a new JFrame called frame2 
     TextArea Reciept = new TextArea ("Receipt For Your Purchase", 20,40);  //Add the Receipt Text Area onto frame2 and show the message 
     Reciept.append("\n\nTime: " + Time.format(cal.getTime())); Reciept.append("\nDate: " + Date.format(cal.getTime()));  //On seperate lines add the Time and the Date (from Calendar) 
     Reciept.append("\n\nYou Have Purchased The Following Item(s): "); //Display the message 
     Reciept.append("\n\n" + Name + "\n" + Amount + " Units" + "\n" + pounds.format(StockData.getPrice(ItemKey)) + " each");         //On a line add the Name and Item Amount followed by the item price (from StockData) on a new line       
     Reciept.append("\n\n\n" + Amount + " Unit(s)" + " at " + pounds.format(StockData.getPrice(ItemKey)) + " each" + "\nTotal = " + pounds.format(Total)); //After 3 lines display the Item Amount and the item price on the same line. On a new line display the Total in a pounds format 
     Reciept.append("\n\n\nThank You For Your Purchase" + "\n\nGoodbye :)");   //Show a message on two seperate lines 
     frame2.pack(); frame2.setSize(375, 380); frame2.setLocation(250, 250); ;frame2.setTitle("Receipt");  //Sets the size, the location, and the title of frame2 
     frame2.setVisible(true); frame2.setResizable(false);    //sets frame2 so that it is visible and not resizable 
     frame2.add(Reciept);            //Display the Reciept Text Area on frame2 
     frame2.setLayout(new FlowLayout(FlowLayout.CENTER));    //It is set to the center of the frame 


     }else{                //Otherwise 
      if (response == JOptionPane.NO_OPTION){       //If the user clicks No or Cancel on the confirm dialog 
                      //Do nothing 
      } 
     } 

代碼檢查庫存

public class CheckStock extends JFrame implements ActionListener { 
JTextField stockNo = new JTextField(7);          //adds a text field for user input 
JTextField AmountNo = new JTextField(5); 
TextArea information = new TextArea(6, 40);         //adds a text area for the output  
JButton check = new JButton("Check Stock");         //adds a button with the text "Check Stock" 
JButton Clear = new JButton(); 
DecimalFormat pounds = new DecimalFormat("£#,##0.00");      //for output to display in decimal and pound format 


public CheckStock() {              //"CheckStock" class 
    setLayout(new BorderLayout());           //adds a new frame for "CheckStock" 
    setBounds(100, 100, 450, 220);           //sets the size and location of the frame 
    setTitle("Check Stock");            //sets the title of the frame 
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);      //user has to click on "Exit" button instead of X sign 

    check.addActionListener(this);           //adds an action listener for the "check" button so when clicked by user, "actionPerformed" class is called 
    JPanel top = new JPanel();            //JPanel is a a container for other components. It is used at the top of the frame 
    add("North", top); 
    top.add(new JLabel("Enter Item Key:"));         //adds a label at the top of tne frame 
    top.add(stockNo);              //adds the "stockNo" text field to the top of the frame  
    top.add(check);               //adds the "check" button to the top of the frame 
    JPanel middle = new JPanel();           //JPanel is a a container for other components. It is used at the middle of the frame 
    add("Center", middle); 
    middle.add(information);            //in the middle of the frame, add the "information" text area 

    setResizable(false);             //frame is not resizable 
    setVisible(true);              //frame is visible 
} 
public void actionPerformed(ActionEvent e) {        //this code is fired once the user runs the ActionListener 
    String key = stockNo.getText();           //string named "key" for the stockNo 
    String name = StockData.getName(key);         //string named "name" for the stockData 
    int Quantity = StockData.getQuantity(key); 
    int NewStock; 
    if (name == null) {              //if there is no input in the text field 
     information.setText("Enter Item Key");        //display the message on the text area 
    } 
    else if (e.getSource() == check) { 

      StockData.getQuantity(key); 
      information.append("" + StockData.getName(key)); 

     information.append("\n New Stock: " + StockData.getQuantity(key));                 //otherwise 
     information.setText(name);             //display the name of the item 
     information.append("\nPrice: " + pounds.format(StockData.getPrice(key))); //display the price of the item using pound format 
     information.append("\nPrevious Stock: " + Quantity);  //display the amount in stock for the item according to StockData 
    } 
} 

}

+0

在Java變量名應該按照慣例被駝峯,所以它應該是:JTextField中amountNo =新的JTextField(5);這不會解決你的問題,雖然... – Adam

回答

0

你沒有初始化objec牛逼Update:你的代碼行應該是

PurchaseItem Update = new PurchaseItem(); 

(作爲另一點我看不到,增加了您所創建的任何的JComponent碼(例如,按鈕,文本字段......)分配給相應類的兩個幀或顯示兩個幀;如果它不包含在你的代碼中,一定要添加這些代碼段)。 最後,如果您需要檢查Updated值的更改的代碼,則可以使用以下最簡單(但不是唯一)的技術創建線程(請參閱Oracle documentation以瞭解線程以及如何使用它們) :

int refreshTime = 1000; // Refresh time in milliseconds 
boolean running = true; // Set it to false if you want to stop the thread 
Runnable r = new Runnable({ 
    @Override 
    public void run() { 
     while(running) { 
      Thread.sleep(refreshTime); 
      // Put here your code to update your frames or your variables 
     }  
}); 
+0

仍然沒有意義給我。我完成了你第一次要求將兩個jcomponents添加到兩個框架中。我在兩個班中都使用了AmountNo,因爲我需要從購買類中獲取信息並將其顯示在checkstock類中。我在此之後卡住了 –

+0

您還需要添加代碼才能顯示相框;請記住,我只發佈了用於從其他類中檢索更改的代碼。如果你仍然陷入困境,我建議你先學習如何使用[Swing](http://docs.oracle.com/javase/tutorial/uiswing/)。對不起,如果我看不到你的代碼,並且知道你的程序需要什麼,我無法幫助你。 – arducode

+0

它在哪裏?我沒有看到任何鏈接 – arducode

相關問題