I am trying to make a Frogger game.
This is a simple JPanel with JLabels on it.
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;
}
It is very difficult to exactly word my question but I basically want the JLabels that are added to the JPanel to be altered and updated when the push() function is called.
Your rotate method is not right...
String first = str.substring(0, str.length());
String second = str.substring(str.length());
Should be something more like
String first = str.substring(0, str.length() - 1);
String second = str.substring(str.length() - 1);
first
will be all the characters excluding the last character and second
will be the last character.
But, remember, you have "spaces" within your String
which may make the process a little more complicated