如何从另一个类的main方法访问变量

时间:2014-05-19 01:07:50

标签: java methods static public

这可能是一个noob问题,但是哦,我需要从我的main方法中收集frameWidth和frameHeight变量


frame.java

public static void main(String[] args) { 
    .....
    .......                                                
    int frameWidth  = frame.getContentPane().getWidth();
    int frameHeight  = frame.getContentPane().getHeight();
}

Board.java

public class board extends JPanel {
    private frame Frame;

    public board() {
        Frame = new frame();
        int FrameWidth = frame.main().frameWidth;
        int FrameWidth = frame.main().frameHeight;
    }
}

访问变量的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

将其传递给构造函数:

private int width = 0, height= 0;
public Board(int width, int height){
  ...
  this.width = width;
  this.height = height;
}

然后在main

Board myBoard = new Board(FrameWidth, FrameHeight);

您的班级现在可以分别以FrameWidthFrameHeight的形式访问变量widthheight

答案 1 :(得分:0)

你需要在Main类中声明棋盘(类应该是大写B)对象,并像这样定义宽度和高度的getter:

public static void main(String[] args) { 
Board board = new Board();                                              
int frameWidth  = board.getWidth();
int frameHeight  = board.getHeight();
}

public class board extends JPanel {
private frame Frame;

public board() {
    Frame = new frame();
    int FrameWidth = frame.frameWidth;
    int FrameWidth = frame.frameHeight;
}
public int getWidth(){
     return frame.frameWidth;
}

public int getHeight(){
    return frame.frameHeight;

}
}