2016-07-08 2 views
2

은 당신이 그렇게점검하십시오 GridBayLayout의 슬롯이 비어있는 경우

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); 

처럼 초기화 된 패널을 그리고 레이아웃은 당신이 볼 수 있듯이

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); 

, 이것은 다음을 추가 제약 GridBayLayout을한다고 가정 해 봅시다 JLabel은 (1, 1)이고 다른 하나는 (1, 3)입니다. 이제 주어진 위치에 레이블이 있는지 여부를 확인하기 위해 프로그램의 조건부 어딘가에 조건을 추가하려고합니다. 예를 들어, 위치 (1, 2)에 레이블이 있는지 (이 경우 레이블이 없는지) 확인하고 싶습니다. 어떤 방법을 사용해야합니까?

+1

나는 이것이 당신 자신, GridBagLayout에를 확장하는 클래스에서 아마 하나를 만드는 방법을해야한다고 생각합니다. –

+0

그렇지만 코드로 무엇을 쓸지는 확신 할 수 없습니다. 어쩌면 panel_playerBuffs.isEmpty (x, y)? – Dragneel

답변

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); 
    }); 
    } 
}