2016-07-30 94 views
-1

我想做一個按鈕,如果用戶點擊它,它會增加int x的值,而在另一個類中我想做同樣的事情,但是,它會增加x的值第一堂課。我做了這個,但是當我傳遞int值時,我得到一個錯誤。請幫忙,我是noob。如何將Int值傳遞給另一個類?

public class one extends JFrame{ 

    private JButton yes; 
    private JButton no; 
    private JLabel one; 
    private JLabel pic; 
    private JLabel two; 
    public static int bla; 

    public static int x; 


    public one(){ 
     super("The title"); 
     setLayout(new FlowLayout()); 

     yes = new JButton("yes"); 
     add(yes); 

     no = new JButton("no"); 
     add(no); 

     Icon one = new ImageIcon(getClass().getResource("one.jpg")); 
     pic = new JLabel(one); 
     add(pic); 

     yes.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent event){ 
      x++; 
      setInt(x); 
      printInt(x); 
      new two().setVisible(true); 

     } 
     } 
     ); 


    no.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent event){ 
      x=0; 
      setInt(x); 
      printInt(x); 
      new two().setVisible(true); 
     } 
     } 
     ); 

    getx(x); 


} 
public void setInt(int y){ 
    y = x; 
} 

public Integer getx(int x){ 
    return x; 
} 

public void printInt(int y){ 
    System.out.printf("%s ", y); 
} 
} 

另一個類

public class two extends JFrame { 

    one satu = new one(); 
    x = x2; 

我把X = X2的兩個類,但我得到了一個error.Please幫助

+1

你得到的錯誤是什麼? –

回答

0

要獲得和增加你的onex值班級(可憐的班級名稱;建議總是以大寫字母開頭,所以你的班級應該是One)你應該這樣做:

One.x++; 

來自其他班級。

0

對於您的addActionListener插入two.x++; 這會增加兩個類中x的值,並且它將使用兩個類中x的現有值。

yes.addActionListener(new ActionListener() { 

    public void actionPerformed(ActionEvent event) { 

    x++; 
    setInt(x); 
    printInt(x); 
    two.x++; // This will increment int x in class two 
    new two().setVisible(true); 

    } 
}); 

對於你的二級。使你的int x靜態,這將允許其他類能夠與它的變量進行交互。

public class two { 
// Make x static so that it can be seen by other public classes 
static int x = 0; 
}