我试图制作一个按钮,如果用户点击它,它会增加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 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放在第二类,但是我收到了错误。请帮忙
答案 0 :(得分:0)
获取并增加x
课程one
的值(不良的班级名称;建议始终以大写字母开始上课,因此您的班级应为{{ 1}})你应该这样做:
One
来自其他班级。
答案 1 :(得分: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;
}