检查GridBayLayout的插槽是否为空

时间:2016-07-08 02:18:36

标签: java swing gridbaglayout

假设你有一个像这样初始化的面板

JPanel panel_playerBuffs = new JPanel();
panel_playerBuffs.setBounds(249, 165, 71, 227);
panel_playerBuffs.setOpaque(false);
panel_playerBuffs.setLayout(new GridBagLayout());
getContentPane().add(panel_playerBuffs);

它的布局是GridBayLayout,具有以下约束

GridBagConstraints gbc = new GridBagConstraints();

gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);

gbc.gridx = 1;
gbc.gridy = 1;
panel_playerBuffs.add(new JLabel("located at 1, 1"), gbc);
gbc.gridx = 1;
gbc.gridy = 3;
panel_playerBuffs.add(new JLabel("located at 1, 3"), gbc);

如您所见,这会在(1,1)处添加JLabel,在(1,3)处添加另一个JLabel。现在我试图在程序中的其他地方添加一个条件来检查在给定位置是否有标签。例如,我想知道位置(1,2)是否有标签(在这种情况下它不是)。我应该使用什么方法?

1 个答案:

答案 0 :(得分:3)

import java.awt.*;
import java.util.Arrays;
import javax.swing.*;

public class GridBayLayoutSlotTest {
  private JComponent makeUI() {
    GridBagLayout layout = new GridBagLayout();
    JPanel panel_playerBuffs = new JPanel();
    panel_playerBuffs.setLayout(layout);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.BOTH;
    gbc.weightx = gbc.weighty = 1.0;
    gbc.insets = new Insets(2, 2, 2, 2);

    gbc.gridx = 1;
    gbc.gridy = 1;
    panel_playerBuffs.add(new JLabel("located at 1, 1"), gbc);
    gbc.gridx = 3;
    gbc.gridy = 1;
    panel_playerBuffs.add(new JLabel("located at 3, 1"), gbc);

    EventQueue.invokeLater(() -> {
      int[][] a = layout.getLayoutDimensions();
      System.out.println(Arrays.deepToString(a));
      System.out.format("isEmpty(%d, %d): %s%n", 2, 1, isEmpty(a, 2, 1));
      System.out.format("isEmpty(%d, %d): %s%n", 3, 1, isEmpty(a, 3, 1));
    });

    return panel_playerBuffs;
  }
  private static boolean isEmpty(int[][] a, int x, int y) {
    int[] w = a[0];
    int[] h = a[1];
    return w[x] == 0 || h[y] == 0;
  }
  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new GridBayLayoutSlotTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}