GUI(视图)启动搞砸了

时间:2016-12-23 17:34:04

标签: java swing model-view-controller

我之前曾帮助创建GUI(感谢@Hovercraft Full Of Eels)。

最初我的GUI在启动时看起来像这样。 enter image description here

当你运行程序时,它看起来像这样。 enter image description here

现在,在我编辑之后,它的启动就像这样。(搞砸了) enter image description here

然后当你运行程序时它看起来像这样。 enter image description here

基本上,启动屏幕看起来很乱,但当你按下按钮时,它会恢复正常,但背景看起来很乱。

代码如下所示

主要课程:

public static void main(String[] args) {
    JFrame f = new JFrame("Envrionment Stimulation");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(input.getGui());    //input is a class that takes the size of the grid and uses it to call the Layout class
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}

这是在获取输入后输入调用的Layout类

public class Layout extends JPanel {

    private static final int WIDTH = 75;
    private static final int SPACING = 15;
    private final GridControls btnAndTxt;
    private final Grid map;

    public Layout(Earth earth, int xCount, int yCount) {

        //Making our borders
        setBorder(BorderFactory.createEmptyBorder(SPACING, SPACING, SPACING,SPACING));
        setLayout(new BorderLayout(SPACING, SPACING));

        //The Map
        map = new Grid(WIDTH, xCount, yCount);

        //Buttons and Text
        btnAndTxt = new GridControls(map, earth);

        //Adding the JPanels.
        add(btnAndTxt, BorderLayout.PAGE_START);
        add(map, BorderLayout.CENTER);
    }
}

接下来将是Grid,它是我们的GUI初始化的方式

public class Grid extends JPanel {

    private final JLabel[][] label;
    private final int xCount, yCount;

    public Grid(int width, int xCount, int yCount) {
        this.xCount = xCount;
        this.yCount = yCount;

        setBackground(Color.BLACK);
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
        setLayout(new GridLayout(yCount, xCount, 1, 1));
        label = new JLabel[yCount][xCount];

        for (int y = 0; y < yCount; y++)
            for (int x = 0; x < xCount; x++) {
                label[y][x] = new JLabel(".", SwingConstants.CENTER);
                label[y][x].setPreferredSize(new Dimension(width, width));
                label[y][x].setBackground(Color.GREEN);
                label[y][x].setOpaque(true);
                label[y][x].setFont(new Font("Ariel", Font.PLAIN, 25));
                add(label[y][x]);
            }
    }

    public void updateGrid(Mappable[][] map) {
        for (int y = 0; y < yCount; y++)
            for (int x = 0; x < xCount; x++) {
                label[y][x].setText(map[y][x] == null ? "." : map[y][x].toString());
            }
    }

    public int getY() {
        return yCount;
    }

    public int getX() {
        return xCount;
    }
}

对于GridControl类,它扩展了Jpanel。我使用了按钮和文本(按钮,文本,按钮)顺序的add()方法,但我没有使用任何布局管理器。这可能是问题吗?初始GUI也没有使用按钮和文本面板的布局管理器。 (布局类保持不变)

* Edit1:更新了网格的外观

当类扩展JPanel时,我有getX()和getY()方法。它覆盖了导致GUI出错的方法。

0 个答案:

没有答案