2016-07-30 95 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; 
}