簡體   English   中英

在(java swing)的網格布局中添加到特定的 position

[英]Adding to specific position in grid layout in (java swing)

    public static void main(String [] args) {
            
        JFrame frame = new JFrame();
        
        JPanel panel= new JPanel();
        panel.setLayout(new GridLayout(4,1));
        
        JLabel l1 = new JLabel("l1");
        panel.add(l1);
        
        frame.add(panel);
        
        frame.pack();
        frame.setVisible(true);

我創建了一個 1 列和 4 行的網格布局,有什么方法可以選擇在哪一行和哪一列添加 label? 我知道 add 方法的 panel.add(Component, int index) 變體,但 idky 我總是收到“線程“main”中的異常 java.lang.IllegalArgumentException:非法組件位置”錯誤。

您可以向每一行添加空白組件(例如JLabel實例),然后通過它們在數組中的索引來管理這些組件隨時間的變化。

public static void main(String [] args) {

JFrame frame = new JFrame();
JPanel panel= new JPanel(new GridLayout(4,1));
JLabel rows[] = new JLabel[4];  //change ui content by managing these now

for(int i=0;i<4;i++){ 
    rows[i] = new JLabel();
    panel.add(rows[i]);
}

//Example: To modify row 3 (i.e. rows[2])
rows[2] = new JLabel("l1");

frame.add(panel);

frame.pack();
frame.setVisible(true);
}

通過這種方式,您還可以更好地訪問可能修改的行維度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM