Adding to specific position in grid layout in (java swing)

2.1k views Asked by At
    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);

I've created a grid-layout with 1 column and 4 rows, is there any way I can choose in which row and column to add the label? I know of the panel.add(Component, int index) variant of the add method, but idky I always get an "Exception in thread "main" java.lang.IllegalArgumentException: illegal component position" error.

1

There are 1 answers

0
macrofox On

You could add blank components to each row (JLabel instances for example) and then manage what those components look like over time via their index in an array.

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

In this manner you would also have better access to potentially modify row dimensions.