简体   繁体   中英

How to access variables from the main method in another class

This is probably a noob question but oh well, I need to collect the frameWidth and frameHeight variables from my main method


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;
    }
}

What is the proper way of accessing the variable?

Pass it into the constructor:

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

Then in your main :

Board myBoard = new Board(FrameWidth, FrameHeight);

Your class will now have access to the variables FrameWidth and FrameHeight as width and height , respectively.

You need to declare the board (the class should be capital B) object in the Main class and define getters for width and height like this:

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;

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM