【问题标题】:Why is this not showing buttons in gridlayout?为什么在gridlayout中没有显示按钮?
【发布时间】:2014-03-30 16:18:29
【问题描述】:

我正在尝试创建所谓的“15 游戏”,它就像一个带有 16 个按钮的幻灯片拼图,其中 15 个按钮的数字为 1-15 和一个空按钮。单击空按钮旁边的按钮将与单击的按钮和空按钮切换位置。但是现在我正在尝试设置由 Swing、gridlayout 和 16 个按钮组成的 gui。但是我不能让它工作,这是我的代码:

package game;

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;



public class TheGame{



public static void main(String[] args){

    TheGame game = new TheGame();

}


public TheGame(){

    JMenuBar menubar = new JMenuBar();
    JFrame frame = new JFrame("15Game");
    GridLayout grid = new GridLayout(4,4,3,3);
    JPanel panel = new JPanel();

    Cell cell1 = new Cell("1");
    Cell cell2 = new Cell("2");
    Cell cell3 = new Cell("3");
    Cell cell4 = new Cell("4");
    Cell cell5 = new Cell("5");

    Cell cell6 = new Cell("6");
    Cell cell7 = new Cell("7");
    Cell cell8 = new Cell("8");
    Cell cell9 = new Cell("9");
    Cell cell10 = new Cell("10");

    Cell cell11 = new Cell("11");
    Cell cell12 = new Cell("12");
    Cell cell13 = new Cell("13");
    Cell cell14 = new Cell("14");
    Cell cell15 = new Cell("15");

    Cell cellEmpty = new Cell("");

    panel.add(cell1);
    panel.add(cell2);
    panel.add(cell3);
    panel.add(cell4);
    panel.add(cell5);

    panel.add(cell6);
    panel.add(cell7);
    panel.add(cell8);
    panel.add(cell9);
    panel.add(cell10);

    panel.add(cell11);
    panel.add(cell12);
    panel.add(cell13);
    panel.add(cell14);
    panel.add(cell15);

    panel.add(cellEmpty);

    panel.setLayout(grid);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

}

}

这里是细胞:

package game;

import javax.swing.JButton;

public class Cell extends JButton {

//Variables

public Cell(String s){

    this.setText(s);

}

当我创建它时,它只弹出一个小的空 gui 窗口,根本没有按钮。为什么会这样,我做错了什么?

【问题讨论】:

  • 在您开始添加按钮之前致电panel.setLayout()。当您添加按钮时,布局的作用是告诉面板按钮的位置。如果在按钮之后添加布局,则效果不佳。您还想将面板添加到框架中,否则也不会有什么好处。

标签: java swing jframe jbutton grid-layout


【解决方案1】:

您需要将包含按钮的面板添加到框架中

frame.add(panel);

【讨论】:

  • 它现在可以工作了,谢谢,但它非常小。我可以使用 setSize(new Dimension(x,y)) 来调整按钮的大小吗?
  • @user3079108 由于您在框架上使用的布局,它很可能很小。你改了吗? JFrame 上的默认布局是 BorderLayout,它不应该抑制框架的大小,只要将其添加到 BorderLayout.CENTER,可以通过向 add 添加另一个参数来完成,如下所示: frame.add(panel, BorderLayout.CENTER);.
  • 您也可以尝试让 Cell 扩展 JFrame 并将按钮添加到其中,然后添加插图和边框以增加单元格大小
  • @user3079108 避免使用setSize。覆盖面板本身的getPreferredSize。其实没有必要继承JButton,只需创建实例并使用
猜你喜欢
  • 2021-03-17
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多