Java Swing Icon not appearing - java

I'm trying to create a piece of code that displays either a smiley face or a sad face when a button is pressed, depending on some value, but it just won't display the image. I know that it's definitely getting past the if/else statements, so I really don't know what is going wrong.
try {
if(data[2] <= ((int) ChronoUnit.DAYS.between(localDate, RTS()))*MnHrs())
{
JLabel lblSmiley = new JLabel(new ImageIcon("C:\\. . .\\smileyface.jpeg"));
panel.add(lblSmiley);
}
else
{
JLabel lblSmiley = new JLabel(new ImageIcon("C:\\ . . . \\sadeface.png));
panel.add(lblSmiley);
}
} catch (Exception e1) {
e1.printStackTrace();
}

It looks like you're loading the icon and adding a new label each time. Instead, you can add the label once and call setIcon() like they show here.
Icon smile = new ImageIcon("C:\\…\\smileyface.jpeg");
Icon sad = new ImageIcon("C:\\…\\sadeface.png");
JLabel lblSmiley = new JLabel();
…
frame.add(lblSmiley);
…
if (…) {
lblSmiley.setIcon(smile);
} else {
lblSmiley.setIcon(sad);
}
Depending on your layout, you may need to change the labels preferred size or add an empty label before you pack() the window.

Probably, it is getting in the panel, but due to dimensions of panel it might be getting placed off screen. Check by modifying the panel dimensions and placing the smiley within that.

Related

Why does a JLabel Component not convert into a JLabel, yet doesn't give any errors?

Okay, so I have this JFrame frame and I'm trying to load all of the components into a JLabel ArrayList. the frame has a LayeredPane and around 20 JLabels scattered across. Some of them have a different z-index/layer index
ArrayList<JLabel> labelList = new ArrayList<>();
for(Component i : frame.getComponents() ) {
if (i instanceof JLabel) {
labelList.add((JLabel) i);
}
}
System.out.println(labelList);
but when I try to print out the ArrayList, it just prints an empty Array.
When I hover over the .getComponents(), it actually shows that all of the JLabels are in fact contained in the method.
And it doesn't give out any errors either, like Component not being able to convert to JLabel etc.
edit: I did as #camickr suggested, and it show that only the contentPane is grabbed. I probably misunderstood how the .getComponents() works.
edit2 just changed the code to:
ArrayList<JLabel> labelList = new ArrayList<>();
for(Component i : layeredPane.getComponents() ) { //layeredPane being the name of the JLayeredPane, suprisingly
labelList.add((JLabel) i);
}
System.out.println(labelList.toArray().length);
And it works.
I am a very dumb indiviudal.
ArrayList<JLabel> labelList = new ArrayList<>();
for(Component i : layeredPane.getComponents() ) { //layeredPane being the name of the JLayeredPane, suprisingly
labelList.add((JLabel) i);
}
System.out.println(labelList.toArray().length);
is the solution. It didn't work due to me trying to grab everything from the frame, but the only thing on the frame was the layered Pane, where all the other components were.

How to dynamically change JFrame background?

I have small problem with changing JFrame background image. First I've added background image with JLabel and application is working good. But now I need to change it dynamically.
I've tried this code :
label = new JLabel(new ImageIcon(Toolkit.getDefaultToo... // old background image
public void changeImage(){
label.setVisible(false);
label2 = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("weatherall.gif"))));
setContentPane(label2); // new Background image
label2.setVisible(true);
repaint();
}
switch (cmb.getSelectedItem().toString()) {
case "ISTANBUL":
x = 0;
changeImage();
//some codes......vs.vs.
break;
Also I'v tried it with timer (TimerTask) every 1 sec. Refreshing frame
Anybody have an idea about this?
Now we need to create JLabel and set it size like background(stretch it) after that just add image into the JLabel and when u want to change it just change the image from same JLabel don't try adding another JLabel,it's not working!!...thats it.
JLabel label = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource(localweather))));
setContentPane(label);//when u want to change background image just replace 'localweather' another image.

Java JFrame MouseListener

I have a JFrame with small squares set as background. Squares are pictures.
Amount of squares depends on JFrame size, so I use ArrayList and I add JLabels to JFrame using:
for(int i = 0; i < squares.size(); i++){
add(squares.get(i));
}
I want to write a method so when mouse enters square it would change its color.
I have implemented MouseListener. However this does not work(it works with normal JLabels):
ArrayList<JLabel> squares = new ArrayList<JLabel>();
.
.
.
#Override
public void mouseEntered(MouseEvent e) {
Object source = e.getSource();
if(source == squares){
System.out.println("AAA");
}
if(source == squares.get(0)){
System.out.println("BBB");
}
}
My question: How do I get element out of ArrayList, so I could set it equal to source and if its equal to source do something?
However this does not work(it works with normal JLabels):
This statement does not make sense. A JLabel is a JLabel. As long as you add the label to the frame it should work. The fact that you created an ArrayList as well doesn't affect how the label works on the frame.
Object source = e.getSource();
You already have the source, so all you need to do is cast it to a JLabel:
JLabel enteredLabel = (JLabel).getSource();
enteredLabel.doSomething(...)

Displaying a JLabel on top of another JLabel

I have the following code:
try {
File file_background = new File(
"C:\\Users\\xxxx\\Desktop\\background.png");
ImageIcon icon_background = new ImageIcon(
ImageIO.read(file_background));
JLabel background = new JLabel(icon_background);
window.setContentPane(background);
File file_car = new File(
"C:\\Users\\xxxxxx\\Desktop\\car.png");
ImageIcon icon_car = new ImageIcon(ImageIO.read(file_car));
JLabel car = new JLabel(icon_car);
car.setVisible(true);
background.add(car);
// TODO Get car showing on top of the background label
} catch (IOException e) {
e.printStackTrace();
}
Where I'm attempting to have the car label show on TOP of the background label. But I'm only getting the background JLabel showing. I'm new to SWING so any suggestions to what steps I'm missing would be great.
..I want to move it a later stage. But right now I want it to show first :)
There are two ways,
1st.
Put JLabel car to JPanel, drawing an Image by using paintComponent, instead of JLabel background (advantage JPanel is container with proper notifications for LayoutManager).
Put JLabel car to JLabel background, but JLabel haven't implemented any LayoutManager, have to set desired.
Advantage all images in JLabel are static, with zero CPU and GPU inpact ad consumption in compare with paintComponent.
Disadvantage JLabel isn't container and with proper notifications for LayoutManager, required a few code lones moreover in compare with JLabel placed in JPanel, for movement (AbsoluteLayout) is quite good solution.
2nd.
Draw both Images by using BufferedImage and Graphics.
Add them both to a JPanel that uses OverlayLayout. It is not ok to add a JLabel to another JLabel.
This code has not gone through a compiler so take it for what it is :)
JPanel panel = new JPanel(new OverlayLayout());
panel.add(background);
panel.add(car);
Works.. Added the following to make it display:
car.setBounds(200, 200, 200, 200);
Apparently it's because by default a null layout manager is used. So setting the bounds of the label will enable it to display since the default size is 0.

How can I put an image in my form?

I'm having a problem. I want to put an image inside a form in Java and I don't know if I'm using a proper technique (found it somewhere in a web page).
private void iconSelect() {
String iconString = "";
if (typeCombobox.getSelectedIndex() == 0) {
iconString = "LP_";
} else if (typeCombobox.getSelectedIndex() == 1) {
iconString = "HP_";
} else if (typeCombobox.getSelectedIndex() == 2) {
iconString = "BP_";
} else if (typeCombobox.getSelectedIndex() == 3) {
iconString = "BS_";
}
if (RB_Gain_Clean.isSelected()) {
iconString = iconString + "Clean";
} else if (RB_Gain_dB.isSelected()) {
iconString = iconString + "dB";
}
ImageIcon icon = new ImageIcon("images/" + iconString + ".jpg");
Image img = icon.getImage();
if (iconGraphLabel.getWidth() > 0 && iconGraphLabel.getHeight() > 0) {
img = img.getScaledInstance(iconGraphLabel.getWidth(), iconGraphLabel.getHeight(), java.awt.Image.SCALE_SMOOTH);
}
icon = new ImageIcon(img);
iconGraphLabel.setIcon(icon);
}
So it actually shows the image and it is resizing but when I resize my form and then make it smaller again, the label doesn't seem to follow the resizing so it stays bigger than the window.
Also, since I'm not very familiar with java's graphics, can anyone tell me how can I control a window resizing event so I redraw the picture? Right now the method is triggered by the combobox and the radiobuttons shown in the code.
Thanks in advance!
edit1: Well the form is my jFrame. The iconGraphLabel is the jLabel I'm putting the image in. I'll try to explain the hierarchy of the parent components.
PlotArea [jPanel] (cardLayout) > plotArea_Image [jPanel] ("cardDraw") > iconGraphPanel [jPanel] > iconGraphLabel
but when I resize my form and then
make it smaller again, the label
doesn't seem to follow the resizing so
it stays bigger than the window
Correct, a JLabel, or any Swing component that uses Icons will paint the Icon at its actual size. If you want the Icon to scale depending on the space available then you need to do custom painting.
The Background Panel classes provides different options for displaying an image (you can just use the Icon,getImage() method). You should also read the section from the Swing tutorial on Custom Painting to better understand how the above code works.
Found a solution. This is the final code:
private void iconSelect() {
iconGraphPanel.removeAll();
ImageIcon icon = new ImageIcon("image.jpg");
BackgroundPanel imagePanel = new BackgroundPanel(icon.getImage(), BackgroundPanel.SCALED);
iconGraphPanel.add(imagePanel);
iconGraphPanel.revalidate();
}
iconGraphPanel is a common jPanel that I use as a place holder. It needs to be set to BorderLayout. The BackgroundPanel class can be found here. The removeAll() is needed so the old image disappears. If you don't put this images start to stack up. Don't know if there is a better way to do that but it works just fine for me. The revalidate() method is needed because we create a new panel so it needs to refresh.
This is mostly camickr work and some other guy from sun forum named Maxideon. I'm just posting for future reference.

Categories