user1466263 user1466263 - 6 months ago 22
Java Question

Java: GridLayout cells appear to merge

First, I am new to programming and this is my first major assignment in java and programming in general so if I am doing some incredibly stupid please tell me so I can correct the bad habit.

Anyway to the problem, I am currently trying to create a gridLayout that has a variable number of rows which will be filled with a label that has text that comes from a file. My problem is specifically on gridLayout were the labels that I do add and are constants seem to be disappearing into one giant cell. So far none of the reasearch I have done has lead to anything so I thought I may as well pose the question.

public void fillTimetablePane(JPanel pane){
int noOfRows = pref.getNoOFPeriods()+1;
pane.setLayout(new GridLayout(noOfRows,4));
pane.setBorder(BorderFactory.createLineBorder(Color.black));
JLabel label = new JLabel();
int i=0;
while (i<4){

switch (i) {
case 0: label.setText("Lesson");
break;
case 1: label.setText("Period");
break;
case 2: label.setText("Room");
break;
case 3: label.setText("Teacher");
break;
}
i++;
pane.add(label);
}
}


here is an image of what happens when I add run the following code:
http://www.freeimagehosting.net/1hqn2

Answer
public void fillTimetablePane(JPanel pane){
    int noOfRows = pref.getNoOFPeriods()+1; 
    pane.setLayout(new GridLayout(noOfRows,4));
    pane.setBorder(BorderFactory.createLineBorder(Color.black));
    //JLabel label = new JLabel();   // from here
    int i=0;                         //   V
    while (i<4){                     //   V
        JLabel label = new JLabel(); // to here
        switch (i) {
        case 0: label.setText("Lesson");
                break;
        case 1: label.setText("Period");
                break;
        case 2: label.setText("Room");
                break;
        case 3: label.setText("Teacher");
                break;
        }
        i++;
        pane.add(label);
    }
}

Ok, why is it not working in your case but works fine in my case? The problem is that you add your label 4 times and change the text inbetween. In a Layout, a single component can only be existing once. So what happens is that when you add your label a second/third/fourth time, its location in the grid will be updated and not added again.

In my case, I actually create a new JLabel in every iteration of the loop and therefore adding a different label to the JPanel.

Hope this is clear enough. Just ask if something is not clear.