首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java框架问题

Java框架问题
EN

Stack Overflow用户
提问于 2015-05-18 14:20:22
回答 2查看 129关注 0票数 0

为了好玩,我正在开发俄罗斯方块,以了解更多关于Java的知识。我对它的JFrame方面有问题。我有实际的游戏部分,这是一个在左边的屏幕上的得分,水平,和高的分数到这个右边。然后,在分数,水平,和高分下,我试图把一个按钮。这是我的代码:

代码语言:javascript
复制
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按钮添加到框架中的部分,那么它将占用整个框架。我尝试了许多不同的选择面板和容器,但我似乎找不到正确的组合,游戏和按钮显示。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-18 14:52:03

正如ACV所说,在不使用LayoutManager的情况下将对象添加到您的JFrame中。当您想要控制事物的显示方式时,应该使用LayoutManager (而不是当您向框架中添加一个对象时)。比如BorderLayoutBoxLayout

例如,使用BorderLayout,您必须添加以下代码:

代码语言:javascript
复制
frame.setLayout(new BorderLayout());
frame.add(game, BorderLayout.CENTER);
frame.add(toggleGhost, BorderLayout.SOUTH);

要理解setSize()setPreferedSize()之间的区别,请参阅this question

最佳实践是将LayoutManager添加到所使用的任何组件(JFrame、JPanel、.)并使用setPreferedSize()setMinimumSize()setMaximumSize()

票数 0
EN

Stack Overflow用户

发布于 2015-05-18 14:24:02

因为您应该使用LayoutManager。而setPreferredSize并不能保证它的大小。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30305701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档