2012-12-01 105 views
0

我有一点问题。这是情况。我在我的主类中有一个数量字段,当点击某些按钮时会增加数量。有一种方法可以让你删除任何订单(我基本上是为餐厅终端进行编程),金额会减少。删除方法被放置在另一个类中。如何将一个类的值返回给另一个类? Java

public void posdel(int pos, JTextField amountFieldGot, int amountGot) 
{ 
    if(slist==null) 
    { 
     JOptionPane.showMessageDialog(null, "No order has been placed yet.",null,JOptionPane.WARNING_MESSAGE); 
    } 
    else 
    { 
     if(pos==1) 
     { 
      reductionAmount = (slist.quantity*slist.price); 
      amountGot = amountGot - reductionAmount; 
      slist=slist.next; 
     } 
     else 
     { 
      int i=1; 
      Node temp=slist; 
      Node prev=null; 
      while(temp.next!=null && i<pos) 
      { 
       prev=temp; 
       temp=temp.next; 
       i++; 
      } 
      if(pos==i) 
      { 
       prev.next=temp.next; 
      } 
      else 
      { 
       JOptionPane.showMessageDialog(null, "Invalid order", null, JOptionPane.ERROR_MESSAGE); 
      } 
     } 
    } 
    amountFieldGot.setText(Integer.toString(amountGot)); 
} 

所以基本上,我有一个在我的GUI中的amountField,我作为参数传递给posdel方法。我也通过金额值作为参数。我得到的新金额是删除第一个订单后的amountGot。 (我没有为其他职位编写代码。) 假设我传递给方法的金额值为30(14 + 16)14 = order 1,16 = order2。 而我的第一个订单的值为14. 因此amountGot = 30 - 14这是16. 而GUI中的amountField得到更新为16. 现在我的订单2成为我的订单1.如果我尝试删除这个, 我amountField得到更新到14.(30-16 = 14)。 所以我猜数量值保持与30本身一样,并没有更新到新amountGot值。有人可以帮我解决这个问题吗?

下面是我的删除按钮的代码。

deleteButton.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       dishDelPos = JOptionPane.showInputDialog("Enter the position of the order to be deleted"); 
       try 
       { 
        dishDeletePosition = Integer.parseInt(dishDelPos); 
        order1.posdel(dishDeletePosition, amountField, amount); 
        repaint(); 
       } 
       catch(NumberFormatException ex1) 
       { 
        JOptionPane.showMessageDialog(null,"This is not a valid position"); 
       } 
      } 
     }); 

回答

1

有几件事。

您可以使该类中的delete方法为static。在您将引用它

value = MyClass.deleteMethod(); 

您可以创建一个新的类来执行方法

MyClass myClass = new MyClass(); 
value = myClass.deleteMethod(); 

可以使用各种各样的指针做到这一点,通过在引用传递到已经存在的实例该类持有删除方法,到你想要调用它的地方。

myFunction(MyClass myClass) 
{ 
    value = myClass.deleteMethod(); 
} 

基本建立你的函数返回一个值

public static int deleteMethod() 
{ 
} 

这个函数返回一个int。

,或者如果你需要返回比这更然后设置类了信息

全局变量
class MyClass 
{ 
    public int value1; 
    public int value2; 
    public String value3; 

    public void deleteMethod() 
    { 
     //does something with global variables 
    } 
} 

现在获取信息调用delete像这样

Myclass myClass = new MyClass(); 
myClass.deleteMethod(); 
value1 = myClass.value1 
value2 = myClass.Value2 
value3 = myClass.Value3 
+1

感谢队友后!帮了很多! :) – Shonu93

+0

没问题broski – WIllJBD

相关问题