minoue10
minoue10

Reputation: 81

JLabel keeps moving depending on values inside

So I'm creating a Java Applet for a game, and I'm using a JLabel to show the current score of the player. The score inside the JLabel updates continuously, however when the score gets from 9 to 10 or 99 to 100, because of the added integer, the position of the JLabel (? or maybe just the text of the JLabel) gets moved.

For instance,

    Score: 9 becomes
   Score: 10

As you can see, the positioning of the word "Score" gets shifted to the left. I want to prevent this from happening. I thought that left-aligning the text would solve the problem, but it definitely hasn't. :/

Here's some relevant code:

label = new JLabel("Score", SwingConstants.LEFT);
label.setFont(new Font("Lucida Grande", Font.PLAIN, 27));
label.setText("Score: " + getScore());
label.setBounds(0, 152, 213, 42);

Thanks in advance.

Upvotes: 0

Views: 671

Answers (3)

elias
elias

Reputation: 15480

Replace:

label.setText("Score: " + getScore());

by:

label.setText(String.format("Score: %-5s", getScore()));

Where 5 means the maximum digits of the score. A negative number aligns to left, otherwise, aligns to right.

Upvotes: 1

martinez314
martinez314

Reputation: 12332

This is all about your layout manager. See this example. Read up on layout managers to learn other ways to go about this. Uncomment to prevent the label from moving.

public class Test
{
    private static int score = 0;

    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        //panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));      

        final JLabel label = new JLabel("Score: " + score);
        //panel.add(Box.createHorizontalStrut(8));
        panel.add(label);
        //panel.add(Box.createHorizontalGlue());

        frame.add(panel);
        frame.pack();
        frame.setVisible(true);


        TimerTask task = new TimerTask() {
            public void run() {
                score++;
                label.setText("Score: " + score);
            }
        };

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(task, 0, 100);
    }
}

Upvotes: 0

SomeJavaGuy
SomeJavaGuy

Reputation: 7347

try using

label.setMinimumSize(new Dimension(100,100));

label.setPreferredSize(new Dimmension(100,100));

had a pretty similar Problem, and as I wrote them together as Attributes for this Components, they were working prett well.

Upvotes: 0

Related Questions