如何将jlabel从arraylist主动设置为jpanel?

wtlkbnrh  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(336)

我想做一个青蛙游戏。
这是一个简单的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。

xmjla07d

xmjla07d1#

你的旋转方法不对。。。

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` 这可能会让过程更复杂一些

相关问题