2016-07-08 11 views
2

Angenommen, Sie ein Panel wie soÜberprüfen Sie, ob ein Steckplatz eines GridBayLayout leer ist

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

Und das Layout ist GridBayLayout mit folgenden Einschränkungen

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

Wie Sie dies fügt sehen initialisiert haben, ein JLabel bei (1, 1) und ein anderes bei (1, 3). Jetzt versuche ich eine bedingte Stelle irgendwo im Programm hinzuzufügen, um zu prüfen, ob an einer bestimmten Position eine Beschriftung vorhanden ist. Ich möchte zum Beispiel herausfinden, ob die Position (1, 2) eine Bezeichnung hat (in diesem Fall nicht). Welche Methode sollte ich dafür verwenden?

+1

Ich denke, dass dies eine Methode sein müßte, die Sie selbst, vielleicht einen in einer Klasse, die GridBagLayout erstreckt. –

+0

Ja, aber ich bin mir nicht sicher, was ich als Code schreiben würde. Vielleicht panel_playerBuffs.isEmpty (x, y)? – Dragneel

Antwort

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