【问题标题】:How to fix layout management如何修复布局管理
【发布时间】:2023-03-11 06:44:01
【问题描述】:

我正在用 Java 克隆 Minesweeper。一切都很好,但我想在顶部添加一个柜台。现在,一些按钮不在屏幕上。我必须更改哪些布局才能修复它?

在添加计数器之前: (https://i.imgur.com/cSKmCGr.jpg)

添加“计数器”后 (https://i.imgur.com/fbMQqQz.jpg)

这是我的代码:

public static JPanel generate() {
            i2w = row*row-ilosc_min;

            przyc = new Sap[row][row];      
            JPanel all = new JPanel();      //panel that contains counter and buttons
            JPanel licznik = new JPanel();  //Counter
            licznik.setBackground(Color.red);
            licznik.setPreferredSize(new Dimension(MyFrame.wym-50, 50));    //counter takes 50 px height and full width of frame

            all.add(licznik);

            JPanel panel = new JPanel();    //Buttons panel
            panel.setVisible(true);
            panel.setLayout(new GridLayout(row, row));                  

            for(int x = 0; x < row; x++) {  //creating buttons
                for(int y = 0; y < row; y++) {
                    Sap sp = new Sap(x, y); //My buttons that extends JButton
                    przyc[x][y] = sp;       
                    panel.add(sp);          //Adding button to panel
                }
            }
            all.add(panel);                 //All contains counter and buttons

            return all;                     //Returning it
        }

当我不创建计数器面板时,按钮就像第二张照片中一样。

抱歉有任何错误,英语不是我的主要语言。

【问题讨论】:

  • 调用 Panel 所在 JFrame 的 pack()。
  • link 现在更糟了。 all.add(panel); Main.getFrame().pack(); return all;

标签: java image button layout grid-layout


【解决方案1】:

首先你知道你的两个面板的默认布局是什么吗? 最短的工作解决方案是让根面板使用BorderLayout 并在根面板对象上添加计数器调用时

add(BorderLayout.NORTH,theCounterObject);

对于按钮的面板,也可以在根面板上调用它

add(BorderLayout.CENTER,theButtonsPanel);

这将在缩短版本中解决它,但最好不要学习 sip 或部分而是所有关于布局管理器的知识,因为它们对于摇摆非常重要,这里是开始 A Visual Guide to Layout Managers

pack() 方法不是必需的,但它是获取完美尺寸的好方法,从评论中这是一个好主意,但问题在于你的布局女巫是FlowLayout,它是面板的默认值,但你应该改变布局后再做。

【讨论】:

    猜你喜欢
    • 2019-04-07
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 2013-08-16
    • 2020-07-27
    相关资源
    最近更新 更多