In the last secong and third line if I say
label.setText("x = ");
The label is moving perfectly but when I change it to
label.setText("x = "+ x);
it does not move. To be specific I want to see the width location of JLabel when it’s moving by variable x!
Beside this I said label.setBounds(x,(getHeight()/2),300,300); which set the Y bound of the label to half of the frame size but it’s not at the middle of frame? Any Idea?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.JFrame;
public class myTiemr {
public static void main(String args[])
{
TimeFrame frame = new TimeFrame();
}
}
class TimeFrame extends JFrame
{
private static final long serialVersionUID = 1L;
private int x = 0;
JLabel label = new JLabel("Here is my label");
public TimeFrame()
{
int d = 10;
setTitle("My Frame");
setSize(500,500);
this.setLocationRelativeTo(null);
add(label);
Timer time = new Timer(d,new TimerListener());
time.start();
setVisible(true);
}
class TimerListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(x>getWidth()){
x=-100;
}
x+=1;
label.setText("x = "+ x);
//label.setText("x = ");
label.setBounds(x,(getHeight()/2),300,300);
}
}
}
The reason that
label.setText("x = "+ x)causes the text to remain still but yet the linelabel.setText("x = ")causes the label to move across the frame is thatrevalidate()is called on theJLabel. This will cause the correct behavior applying the current layout manager’s rules (namelyBorderLayoutin this case).When the text does not change,
revalidate()is never called.As @Sébastien Le Callonnec suggested setting no layout on the frame will cause
to move as desired.