Question

I have a list of JLabels that I am insterting into my JPanel:

avatarGridPanel.add(new JLabel(new ImageIcon("images/gui/orc_male.png", "Orc Male")));
avatarGridPanel.add(new JLabel(new ImageIcon("images/gui/human_male.png", "Human Male")));
avatarGridPanel.add(new JLabel(new ImageIcon("images/gui/tundrian_male.png", "Tundrian Male")));
avatarGridPanel.add(new JLabel(new ImageIcon("images/gui/brimlock_male.png", "Brimlock Male")));

I want to add tooltiptext to each of them. Is there any better way than to use a temp variable to hold one of their values and then keep re-using it?

JLabel temp = new JLabel();
temp = new JLabel(new ImageIcon("images/gui/human_male.png", "Human Male"));
temp.setToolTipText("Human Male");
avatarGridPanel.add(temp);

I tried doing something like this(below) but could not get it to work. Thanks for any help!

avatarGridPanel.add(new JLabel(new ImageIcon("images/gui/human_male.png", "Human Male")).setToolTipText("Human Male"));
Was it helpful?

Solution

You could create a function to create these for you. I do it sometimes when I have a big array and need to the same thing over and over:

private static JLabel makeLabel(String path, String name) {
    JLabel label = new JLabel(new ImageIcon(path, name));
    label.setToolTipText(name);
    return label;
}

Then elsewhere in that class:

avatarGridPanel.add(makeLabel("images/gui/orc_male.png", "Orc Male"));

OTHER TIPS

You can use a "temp" variable, but if you do you don't want to first create an empty JLabel and then right after that a new JLabel with icon and text.

But how about creating a helper method?

...
avatarGridPanel.add(createLabel("images/gui/human_male.png", "Human Male"));
...

private JLabel createLabel(String iconPath, String description) {
    JLabel label = new JLabel(new ImageIcon(iconPath, description));
    label.setToolTipText(description);
    return label;
} 

You could create a method where you pass in the image location, the text and the tooltip text to avoid all that code repetition.

This should work

private static JLabel createImageLabel(String imageLocation, String name, String toolTipText) {
    JLabel temp  = new JLabel(new ImageIcon(imageLocation, name));
    temp.setToolTipText(toolTipText);
    return temp;
}

There are ways to do that in one line but nothing really clean nor elegant.

Anyway, in most cases it isn't a good idea to create new instances of a class and not storing them in, at least, a local variable (even for a temporary usage).

So, the best thing to do here is to have this temp variable or delegate the code to something else (method/builder).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top