【问题标题】:determining if a cell is occupied in a gridbag layout确定单元格是否在网格包布局中被占用
【发布时间】:2012-08-27 15:17:47
【问题描述】:

我在网格包布局中有 n 个组件。这些组件的网格宽度和网格高度可以为 1 或更大。可以有 n 行,但每行最多只有 2 个组件。

是否有检查网格袋单元是否已被占用。所以如果组件'A'的高度为2并且在单元格0x0中,我可以找到0x1是否被占用并跳过在那里放置组件?

我考虑了一个 boolean[][] 数组,但最大行数和列数会根据布局而改变(用户可以上下移动组件,删除它们,然后添加它们)。

另一个注意组件被添加为
0x0 -> 0x1
1x0 -> 1x1

【问题讨论】:

    标签: java swing awt layout-manager gridbaglayout


    【解决方案1】:

    好的,所以我最终解决了这个问题,我制作了 ArrayListBoolean[]s。在我的例子中,我知道只有 2 列。如果你不确定你可能想做一个 2d ArrayList。

    private void updateTableLayout() {
            //tableHolderPanel holds the JXTitledPanels
            GridBagLayout gbl = (GridBagLayout) tableHolderPanel.getLayout();
            List<Boolean[]> occupied = new ArrayList<Boolean[]>();
            occupied.add(new Boolean[]{false, false});
            int x = 0;
            int y = 0;
            boolean notPlaced;
            for (TableJXPanel table : tableList) {
                GridBagConstraints gbc = gbl.getConstraints(table);
                notPlaced = true;
    
                while (notPlaced) {
                    if (!occupied.get(y)[x]) {
                        //Set true to first cell occupied
                        occupied.get(y)[x] = true;
                        if (gbc.gridwidth > 1 && x == 0) {
                            occupied.get(y)[1] = true;
                        }
    
                        //Add any additional cells and set them.
                        for (int i = 0; i < gbc.gridheight - 1; i++) {
                            if (gbc.gridwidth > 1) {
                                occupied.add(new Boolean[]{true, true});
                            } else {
                                occupied.add(new Boolean[]{false, false});
                                occupied.get(y+1)[x] = true;
                            }
                        }
                        //Add new row for next comparison
                        if(occupied.get(y)[1])
                            occupied.add(new Boolean[]{false, false});
    
                        //signal that the table was placed
                        notPlaced = false;
                        gbc.gridy = y;
                        gbc.gridx = x;
                    }
                    if (x == 0) {
                        x++;
                    } else {
                        x = 0;
                        y++;
                    }
                }
                tableHolderPanel.remove(table);
                tableHolderPanel.add(table, gbc);
            }
        }
    

    这可能不是最好的代码,所以如果有人看到应该更改的内容,请发表评论。

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 2016-07-13
      • 1970-01-01
      相关资源
      最近更新 更多