我有两个Java类:
BoardManager& 板
BoardManager是主要类。里面有一块板子:
public BoardManager(){
Board b = new Board();
}
public methodToBeCalled(){}
public static void main(String[] args) {
new BoardManager();
}
Board是用户界面。当用户按下接口上的按钮时我想要它然后调用BoardManager类中的方法,但这显然存在问题,我不确定如何解决它。
一种解决方案是将主要方法移到Board中,所以:
BoardManager boardManager;
public Board(){}
public void buttonPressed(){
boardManager.methodToCall();
}
public static void main(String[] args) {
boardManager = new BoardManager();
}
但这只会引发关于静态和非静态等的错误。
解决方案?谢谢!
答案 0 :(得分:0)
要么:
class Board{
static BoardManager boardManager;
public Board(){}
public void buttonPressed(){
boardManager.methodToCall();
}
public static void main(String[] args) {
boardManager = new BoardManager();
}
}
或者这个:
class Board {
BoardManager boardManager;
public Board(){ }
public void buttonPressed(){
boardManager.methodToCall();
}
public static void main(String[] args) {
Board b = new Board();
b.boardManager = new BoardManager();
}
}
您无法从静态方法(main)调用非静态字段(BoardManager)。详细了解静态关键字。