我正在创建一个俄罗斯方块游戏,并希望用户能够从3种不同的尺寸中选择他们的电路板尺寸。我有一个Board后端处理右,左,下,下降动作,我有一个BoardGUI,可以创建形状和动画。因此,在更新大小时,我需要更新后端和我的GUI板。我的尺寸不断初始化为10 x 20,这是默认尺寸。
这是我的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();
}
这是我设置尺寸
的MainGUIprivate 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
}
});
}
答案 0 :(得分:3)
您保存变量,但从不重置首选大小。
this.setPreferredSize(new Dimension(myWidth * BLOCK_WIDTH, myHeight * BLOCK_WIDTH));
问题是你不应该使用setPreferredSize()方法。这使得尺寸固定不动态。
相反,您应该覆盖面板的getPreferredSize()
方法。类似的东西:
@Override
public Dimension getPreferredSize()
{
return new Dimension(myWidth * BLOCK_WIDTH, myHeight * BLOCK_WIDTH));
}
这将允许在Swing需要时动态计算大小。
在更新需要调用的变量之后,现在在panel.setSize()
方法中:
revalidate();
repaint();
因此可以调用布局管理器,并考虑面板的新大小。