为了好玩,我正在开发俄罗斯方块,以了解更多关于Java的知识。我对它的JFrame方面有问题。我有实际的游戏部分,这是一个在左边的屏幕上的得分,水平,和高的分数到这个右边。然后,在分数,水平,和高分下,我试图把一个按钮。这是我的代码:
public class Tetris implements World {
boolean pause = false; // for pausing the game
boolean end = false; // for ending the game
static int score = 0; // score. Increments of 100
static int level = 1; // indicates level. Increments of 1.
static int highScore = 1000; // indicates the overall high score
static final int ROWS = 20; // Rows of the board
static final int COLUMNS = 10; // Columns of the board
Tetromino tetr, ghost, od1, od2, od3; // Tetr is the tetromino currently following. Ghost is the shadow blocks.
SetOfBlocks blocks; //SetOfBlocks on the ground
Tetris(Tetromino tetr, SetOfBlocks blocks) {
this.tetr = tetr;
this.blocks = blocks;
}
//Main Method
public static void main(String[] args) {
BigBang game = new BigBang(500, new Tetris(Tetromino.pickRandom(), new SetOfBlocks()));
JFrame frame = new JFrame("Tetris");
//JButton
JButton toggleGhost = new JButton("Toggle Ghost");
toggleGhost.setFont(new Font("default", Font.PLAIN, 10));
Dimension size = new Dimension(100, 25);
toggleGhost.setPreferredSize(size);
toggleGhost.setLocation(217, 60);
//frame
//frame.getContentPane().add( toggleGhost );
frame.getContentPane().add(game);
//frame.getContentPane().add( toggleGhost );
frame.addKeyListener(game);
frame.setVisible(true);
frame.setSize(Tetris.COLUMNS * Block.SIZE + 150, Tetris.ROWS * Block.SIZE + 120); // Makes the board slightly wider than the rows
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.start();BigBang是一个扩展JComponent并主要处理计时器的类。如果我取消了将toggleGhost按钮添加到框架中的部分,那么它将占用整个框架。我尝试了许多不同的选择面板和容器,但我似乎找不到正确的组合,游戏和按钮显示。
发布于 2015-05-18 14:52:03
正如ACV所说,在不使用LayoutManager的情况下将对象添加到您的JFrame中。当您想要控制事物的显示方式时,应该使用LayoutManager (而不是当您向框架中添加一个对象时)。比如BorderLayout或BoxLayout。
例如,使用BorderLayout,您必须添加以下代码:
frame.setLayout(new BorderLayout());
frame.add(game, BorderLayout.CENTER);
frame.add(toggleGhost, BorderLayout.SOUTH);要理解setSize()和setPreferedSize()之间的区别,请参阅this question。
最佳实践是将LayoutManager添加到所使用的任何组件(JFrame、JPanel、.)并使用setPreferedSize()、setMinimumSize()或setMaximumSize()。
发布于 2015-05-18 14:24:02
因为您应该使用LayoutManager。而setPreferredSize并不能保证它的大小。
https://stackoverflow.com/questions/30305701
复制相似问题