如何主动将JLabel从ArrayList设置为JPanel?

时间:2015-04-28 03:14:35

标签: java arraylist jlabel

我正在尝试制作一个Frogger游戏。

这是一个简单的JPanel,上面有JLabel。

public class PlayField extends JPanel implements KeyListener{

ArrayList<JLabel> rows = new ArrayList<JLabel>();
Random g = new Random();

public PlayField(int length){  //length is the number of rows

    generateField(length);
    for(JLabel label : rows){
        add(label);  //here is where I add all of the labels to the panel
    }
}

public void generateField(int length){          //generates our JLabels in the ArrayList..

    for(int i = 0; i < length; i++){

        JLabel lbl = new JLabel();
        int obstaclePos = g.nextInt(5);
        switch (obstaclePos){

            case 0: lbl.setText(" X — — — —");
            break;
            case 1: lbl.setText(" — X — — —");
            break;
            case 2: lbl.setText(" — — X — —");
            break;
            case 3: lbl.setText(" — — — X —");
            break;
            case 4: lbl.setText(" — — — — X");
            break;


        }

        lbl.setBounds(0,20*i,80,20);
        rows.add(lbl);  //adding the JLabels to my arraylist
        lbl.setName("row" + i);

    }

}

public void push(){  //scrolls text one to the right and puts last character at the beginning

    for(JLabel label : rows){
        label.setText(rotate(label.getText()));
    }

}

public String rotate(String str){  //cycles text one to the right, and wraps last character

    String first = str.substring(0, str.length());
    String second = str.substring(str.length());
    return second+first;

}

很难确切地说出我的问题,但我基本上希望在调用push()函数时更改和更新添加到JPanel的JLabel。

1 个答案:

答案 0 :(得分:1)

你的旋转方法不正确......

String first = str.substring(0, str.length());
String second = str.substring(str.length());

应该更像是

String first = str.substring(0, str.length() - 1);
String second = str.substring(str.length() - 1);

first将是排除最后一个字符的所有字符,而second将是最后一个字符。

但是,请记住,你String中有“空格”可能会使这个过程变得更复杂