【问题标题】:JFrame not resizing with JPanelJFrame 不使用 JPanel 调整大小
【发布时间】:2014-02-07 12:24:16
【问题描述】:

我正在制作一个扫雷程序,我需要实现一个功能,用户可以选择调整地雷所在的网格的大小。我已经完成了这个,但是当我制作更大的电路板时,JFrame 并没有变得更大。

这是当用户想要调整板子大小时发生的方法

public void mouseClicked(MouseEvent e) {
    if(e.getSource() == quitButton && e.getButton() == 1){
        System.exit(0);
    }
    // if I hit the reset size button this happens
    if(e.getSource() == setDimension){
        for (int r = 0; r < size; r++)
            for (int c = 0; c < size; c++){
                gameBoard.remove(board[r][c]); // removes the buttons from the board
            }
        inputSizeAndMines(); // lets the user choose the size and amount of mines
        game = new MineSweeperGame(size, mines); // remakes the game 
        setBoard(); // adds new buttons based on what the user entered
        displayBoard(); // makes visuals for the board
        revalidate();
        repaint();
    }

这是将面板添加到 JFrame 的类

public class MineSweeper {


    /**********************************
     * Main class that does everything
     **********************************/
    public static void main(String[] args) {
        JFrame frame = new JFrame("MineSweeper");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        MineSweeperPanel panel = new MineSweeperPanel();
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }

}

任何帮助将不胜感激

【问题讨论】:

    标签: java swing jframe jpanel


    【解决方案1】:

    重新计算面板的首选尺寸后,再次在框架上调用pack

    【讨论】:

    • 当框架在单独的类中时我该怎么做?
    • 您的framestatic,在我看来这不是一个好主意,或者您可以使用SwingUtilities.getWindowAncestor
    • 哦,那是我的错,我正在尝试其他不起作用的东西,忘记改变它。这有什么区别吗?顺便谢谢你的帮助
    • 这意味着任何东西都可以从任何地方访问您的框架参考......但鉴于我可以使用SwingUtilities 来做同样的事情,它的任何问题都更少。如果您更改参考(意外或其他原因)或想要多个游戏帧,唯一的问题就出现了
    • 我在我没有将 JFrame 作为静态或作为实例变量的地方进行了编辑。我有什么不同的办法吗?
    猜你喜欢
    • 1970-01-01
    • 2011-10-03
    • 2012-05-16
    • 2012-09-01
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多