Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding JLabel text over JLabel Icon. Using the same JLabel text

Sorry about the title being vague but I couldn't think of what I wanted to do in the title. Anyway, for text over image, I have used a JLabel text and added it to the Icon.

    JLabel icon = new JLabel(new ImageIcon);
    icon.setLayout(new GridBagLayout());
    add(icon);

    JLabel text = new JLabel();
    text.setText(language.getString("translation"));
    text.setLocation(10, 10);
    text.setSize(text.getPreferredSize());
    icon.add(text);

I am doing i18n for my app and every time I switch locales, it adds the same JLabel to the previous one so you can see the text on top of each other. How do I use the same Jlabel instead of adding a new one on top?

Thanks

like image 757
user3354252 Avatar asked Dec 20 '22 17:12

user3354252


2 Answers

Keep the text label as a field of class and just call setText() rather than recreating/adding them.

like image 24
StanislavL Avatar answered Dec 22 '22 07:12

StanislavL


I think what you want to create is a JLabel with custom icon

You should create a JLabel and set it's icon, like this:

JLabel label = new JLabel(language.getString("translation"));
label.setIcon(new ImageIcon(/* path of your icon */));

And if you want fix the text overlap, you should set the text alignment like this:

lblText.setHorizontalTextPosition(JLabel.CENTER);

like image 140
Gabriel Câmara Avatar answered Dec 22 '22 07:12

Gabriel Câmara