Java - how to use methods - java

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"));

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"));

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).

Related

I want to replace a JLabel with another JLabel but keep it in the same position, is this possible?

Here is the code that I am trying to edit:
game = new JPanel();
ImageIcon bbb = new ImageIcon("bbb.gif");
JLabel bbbl = new JLabel(bbb);
ImageIcon bbbH = new ImageIcon("bbbH.gif");
JLabel bbbHl = new JLabel(bbbH);
game.setLayout(new GridLayout(2,2));
game.add(bbol);
game.add(bbgl);
game.add(bbgrl);
game.add(bbbl);
if (flashed == 1)
{
game.remove(bbol);
game.add(bboHl);
}
else
{
}
I want the JLabel bboHl to go in the same position as the JLabel bbol however there are other JLabels after this one, 3 more to be exact, therefor explaining why the layout is (GridLayout(2,2))
Would I need to change the layout?
Removing/adding components to the layout is way too expensive.
From what I understand, you just want to toogle an image :
Add only one JLabel, and use setIcon on it to change the image.
game = new JPanel();
ImageIcon bbb = new ImageIcon("bbb.gif");
ImageIcon bbbH = new ImageIcon("bbbH.gif");
JLabel bbbl = new JLabel(bbb);
game.setLayout(new GridLayout(2, 2));
game.add(bbol);
game.add(bbgl);
game.add(bbgrl);
game.add(bbbl);
if (flashed == 1) {
bbbl.setIcon(bbbH);
} else {
bbbl.setIcon(bbb);
}
Let say if there are multiple labels like label1 ,label2 , label3etc. And you want to set them on the position of label bbo1. Then it can be done by getting the location of label bbo1 and setting it to all other labels.
For Example
label1.setLocation(bbo1.getLocation());
label2.setLocation(bbo1.getLocation());
label3.setLocation(bbo1.getLocation());

JLabels created from an ArrayList<String> won't appear * when others will *

I am not new to GUI or swing programming, just as a disclaimer.
In my class that extends JPanel, I have an ArrayList< String > opponentNames that I want to use to create JLabels. I have an ArrayList< JLabel > labels to contain the JLabels. I used this list and also I tried to add directly to the frame which is why both are in the code block below. I know that I should just use one.
for(String s : opponentNames){
JLabel label = new JLabel(s);
label.setVisible(true);
labels.add(label);
this.add(label);
}
Then later on I added test JLabels in the same exact manner without using my ArrayList < String >:
for(int i = 0; i < 5; i++){
JLabel label = new JLabel(""+i);
label.setVisible(true);
labels.add(label);
this.add(label);
}
This adds 5 JLabels to my panel.
Later on I tried adding all of ArrayList < JLabel > labels again to the panel:
for(JLabel l : labels){
System.out.println(l.getText());
System.out.println(l.isVisible());
this.add(l);
}
In the console, every single label prints out with the proper text (the numbers and the Strings from ArrayList < String> opponentNames) but the only things that appear on the screen are the JLabels 0...4, twice.
TL;DR: All of my JLabels exist and are set visible, but only some are appearing on the screen.
edit: I had a typo: is supposed to be label.setVisible(true); in the first for loop. This code here is not copied and pasted, it is greatly simplified. That was/is not the error in my code.
edit2: Here is runnable code. Of course when I tested it my problem isn't happening here, so that tells me that there is an issue elsewhere in my code.
import javax.swing.JFrame;
public class JLabelTestMain {
public static void main(String[] args) {
TestJLabelCode panel = new TestJLabelCode();
JFrame frame = new JFrame();
frame.setContentPane(panel);
frame.pack();
frame.validate();
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
}
}
Then the other class:
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TestJLabelCode extends JPanel{
private ArrayList<String> opponentNames;
private ArrayList<JLabel> labels;
public TestJLabelCode(){
opponentNames = new ArrayList<String>();
labels = new ArrayList<JLabel>();
opponentNames.add("client1");
opponentNames.add("client2");
opponentNames.add("client3");
opponentNames.add("client4");
opponentNames.add("client5");
for(String s : opponentNames){
JLabel label = new JLabel(s);
label.setVisible(true);
labels.add(label);
this.add(label);
}
for(int i=0; i<5; i++){
JLabel label = new JLabel(""+i);
label.setVisible(true);
labels.add(label);
this.add(label);
}
for(JLabel label : labels){
System.out.println(label.getText());
System.out.println(label.isVisible());
add(label);
}
}
}
I assume this, so your class, extends JFrame (or another Swing container, like a JPanel) and that's why you use this.add().
In the first for loop, you add the String s to your frame, not the JLabel.
It should be
for(String s : opponentNames){
JLabel label = new JLabel(s);
label.setVisible(true);
labels.add(label);
this.add(label);
}
instead of
for(String s : opponentNames){
JLabel label = new JLabel(s);
s.setVisible(true);
labels.add(s);
this.add(s);
}
Your current code shouldn't even compile, since String doesn't contain a method setVisible(boolean) and if your ArrayList is generic and thus only takes JLabels.
I found out the source of my error. This is a very small piece of a very large networked game. I accidentally created this panel twice. I was repainting the first instance of it, which was initialized without client/opponent names, even though I was properly updating the second instance of it. The print statements in the console were coming from the second instance, while the first instance was the only one displayed.
Thank you to #HovercraftFullOfEels and #Zhedar for your help.

how to Put JLabel text over a JTextField

how to add a JLabel simple text over/above a JTextField.
I tried many commands as you can see in my code but nothings works.
this is a snapshot of my code
private JPanel createTextPanel() {
int panelWidth = PANEL_SIZE.width;
int panelHeight = PANEL_SIZE.height/3;
Dimension panelSize = new Dimension(panelWidth,panelHeight);
JPanel textPanel = new JPanel();
textPanel.setPreferredSize(panelSize);
//textPanel.setLayout(null);
/* Add text */
JLabel Text_RED = new JLabel();
Text_RED.setText("Red");
//Text_RED = new JLabel("\nRED\n");
//Text_RED.setHorizontalTextPosition(SwingConstants.TOP);
//Text_RED.setVerticalAlignment(SwingConstants.TOP);
Red = new JTextField(3);
//Red.setVerticalAlignment(JTextField.TRAILING );
Red.setLocation(100,100);
//Red.setLocation(50, 50);
JLabel Text_Green = new JLabel("Green");
Green = new JTextField(3);
JLabel Text_Blue = new JLabel("Blue");
Blue = new JTextField(3);
//setLayout(new GridLayout(2,2,10,10));
textPanel.add(Text_RED);
textPanel.add(Red);
textPanel.add(Text_Green);
textPanel.add(Green);
textPanel.add(Text_Blue);
textPanel.add(Blue);
return textPanel;
}
Suggestions:
Don't use null layouts and absolute positioning. While it seems initially that using these tools is the easiest way to create complex GUI's, it's really a newbie fallacy, as the more you understand and use the layout managers, the more you'll find that they make the job of creating GUI's much easier, and the results much more attractive.
Learn about and use the layout managers. Tutorial link.
Consider using a BorderLayout and adding your JLabel BorderLayout.CENTER and the JTextField at BorderLayout.PAGE_END. As a side note, I generally avoid placing JTextFields in a BorderLayout.CENTER position since this will cause horizontal stretching of the field if the GUI changes size, which I don't think is aesthetically pleasing.

Loading an ImageIcon onto an existing JLabel

I already know that a JLabel can use an ImageIcon in the declaration of the JLabel, like this.
JLabel stick = new JLabel(new ImageIcon("stickPicture.gif"));
My question is, how to assign the picture to the JLabel after declaration. For example (this isn't actually the code that works, this is just the technique that I thought might have worked)
JLabel stick = new JLabel();
stick = new ImageIcon("stickPicture.gif"));
Kind of an odd question, just wondering if it can be done.
Use JLabel#setIcon(Icon).
JLabel stick = new JLabel();
stick.setIcon(new ImageIcon("stickPicture.gif"));

Best way to add a String in a JFrame

which is the best way to add formated string in jframe.
Previously I was trying to add jlabel
If you want to display some text in a window, yes, adding a JLabel to your JFrame is fine.
Just create an instance of the font you want and assign it to the JLabel using setFont.
Here is a code samle (taken from here):
Font font = new Font("Jokerman", Font.PLAIN, 35);
JLabel textLabel = new JLabel(textMessage);
textLabel.setFont(font);

Categories

Resources