Java 如何将Int值传递给另一个类?
我试图制作一个按钮,如果用户点击它,它将增加int x的值,在另一个类中,我想做同样的事情,但它将从第一个类中增加x的值。我做了这个,但是当我传递int值时出错了。请帮忙,我是noobJava 如何将Int值传递给另一个类?,java,swing,Java,Swing,我试图制作一个按钮,如果用户点击它,它将增加int x的值,在另一个类中,我想做同样的事情,但它将从第一个类中增加x的值。我做了这个,但是当我传递int值时出错了。请帮忙,我是noob public class one extends JFrame{ private JButton yes; private JButton no; private JLabel one; private JLabel pic; private JLabel two;
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放在第二类上,但我得到了一个错误。请帮助获取并增加你的
one
类的x
值(糟糕的类名;建议总是以大写字母开头类名,因此你的类应该是one
)你应该做:
One.x++;
来自另一个类。对于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);
}
});
给你的二班。将intx设为静态,这将允许其他类能够与其变量交互
public class two {
// Make x static so that it can be seen by other public classes
static int x = 0;
}
您得到的错误是什么?