简体   繁体   中英

How to add a space before the text in a JLabel?

I have created a JLabel and what to put some text in it. But when i look at the result, the text to close to the edge of the screen. So i want to add a space " " before it so that it moves further away from the edge of the screen. But this does not work, the space does not get added no matter how many spaces i put before the text.

JLabel nameLabel= new JLabel("Name");
nameLabel.setText("   Hello my name is tom.");
add(nameLabel, BorderLayout.CENTER);

As you can see above, i have tried to add a space before the hello to make it move further away from the edge of the screen. But the space just doesnt show up when i run the program.

I know i can move the label a bit right, but i am only supposed to you this layout. I just want to find out if there is away to add a space before the text that shows up when the program is run.

You could consider using an EmptyBorder , for example...

JLabel nameLabel= new JLabel("Name");
nameLabel.setBorder(new EmptyBorder(0, 20, 0, 0));
nameLabel.setText("Hello my name is tom.");
add(nameLabel, BorderLayout.CENTER);

Have a look at How to Use Borders for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM