Java框架问题

标签 java swing layout-manager

我开发俄罗斯方 block 是为了好玩/了解更多关于 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 的类,主要处理 Timer。如果我取消注释将toggleGhost按钮添加到框架的部分,那么它会占据整个框架。我已经尝试了许多不同的面板和容器替代方案,但我似乎找不到游戏和按钮显示的正确组合。

最佳答案

因为你应该使用 LayoutManager 。并且 setPreferredSize 不保证大小。

关于Java框架问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30305701/

相关文章:

Javalite 框架 - 定位现有 FreeMarker 模板的问题

java - 在jframe上显示图像

java - 为什么除非我提取文件,否则我的 Jar 不会运行?

java - 边框布局与网格布局冲突

java - 在 javavfx 中创建一个椭圆,其中缩放是从左上角(如矩形)而不是中心开始

java - 使用自定义 header 使用 Kafka 消息

java - 向使用泛型扩展父级的子级添加更多泛型类型

java - 如何更改 JTable 中单元格的背景和格式

java - 按钮大小 (Java)

java - 如何在不使用 swing 类/方法的情况下嵌套布局管理器?