2

首先,我是编程新手,这是我在 Java 和一般编程方面的第一个主要任务,所以如果我做了一些非常愚蠢的事情,请告诉我,这样我就可以改正这个坏习惯。

无论如何,对于这个问题,我目前正在尝试创建一个 gridLayout ,它具有可变数量的行,这些行将填充一个标签,该标签具有来自文件的文本。我的问题特别是在 gridLayout 上,我添加的标签和常量似乎正在消失在一个巨大的单元格中。到目前为止,我所做的研究都没有导致任何结果,所以我想我不妨提出这个问题。

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

这是我添加运行以下代码时发生的情况的图像: http ://www.freeimagehosting.net/1hqn2

4

2 回答 2

6

您添加了 4 次相同的标签。将新的 JLabel 移动到您的 while 循环中

于 2012-06-19T12:19:24.307 回答
6
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.

于 2012-06-19T13:05:22.420 回答