0
我創建了一個俄羅斯方塊遊戲,並希望用戶能夠從3種不同的尺寸中選擇他們的棋盤大小。我有一個Board後端處理右,左,下,下降動作,並且我有一個BoardGUI可以創建形狀並對其進行動畫處理。所以當更新大小時,我需要更新後端和我的GUI板。我的尺寸不斷被初始化爲10 x 20,這是默認尺寸。變體不被setters更新
這裏是我的BoadGUI片斷(我刪除了所有不必要的代碼,我可能錯過了一些東西,對不起)
public class BoardGUI extends JPanel implements Observer {
private static final int BLOCK_WIDTH = 20;
private Board myBoard;
private MainGUI myFrame;
private int myWidth;
private int myHeight;
public BoardGUI(MainGUI theFrame, int theWidth, int theHeight){
myWidth = theWidth;
myHeight = theHeight;
this.myBoard = new Board(myWidth, myHeight);
this.myFrame = theFrame;
setupComponents();
myBoard.newGame();
}
public Board getBoard() {
return myBoard;
}
public void setPanelSize(int theWidth, int theHeight){ // gets correct values
this.myWidth = theWidth;
this.myHeight = theHeight;
}
private void setupComponents() {
setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(myWidth * BLOCK_WIDTH, myHeight * BLOCK_WIDTH)); // setting this panel size
System.out.println(myWidth + " " + myHeight); // DOES NOT PRINT CORRECT SIZE
myFrame.pack();
}
這裏是我的MainGUI,我設置的大小
private int myWidth;
private int myHeight;
public MainGUI() {
super();
myWidth = 10;
myHeight = 20;
}
/**
*
*/
private static final long serialVersionUID = -5056050661369885282L;
private JMenuBar myMenuBar;
public void start() {
setTitle("Tetris");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myEastPanel = new JPanel(new BorderLayout());
NextPiece nextPanel = new NextPiece();
myBoardGUI = new BoardGUI(this, myWidth, myHeight);
myMainBoard = myBoardGUI.getBoard();
setResizable(false);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public JMenuBar createMenuBar() {
myMenuBar = new JMenuBar();
myWindow = new JMenu("Window");
final JFrame frame = this;
myMenuBar.add(myWindow);
setWindowSize();
myMenuBar.setVisible(true);
return myMenuBar;
}
private void setWindowSize() {
ButtonGroup group = new ButtonGroup();
JCheckBox def = new JCheckBox("Default");
JCheckBox size1 = new JCheckBox("150 x 250");
myWindow.add(def);
myWindow.addSeparator();
myWindow.add(size1);
group.add(def);
group.add(size1);
JFrame frame = this;
def.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
myWidth = 10;
myHeight = 20;
myBoardGUI.setPanelSize(myWidth,myHeight); //setting here
}
});
size1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// myBoardGUI.setPanelSize(15, 25);
myWidth = 15;
myHeight = 25;
myBoardGUI.setPanelSize(myWidth,myHeight); // Setting here
}
});
}
這對我們來說是相當不錯的(如果你能創建併發佈一個有效的[mcve],那麼對於我們來說這可能會幫助你在這裏快速得到答案)(請閱讀鏈接以瞭解這個有用工具的重要細節) ,我們可以運行,測試和修改。 –