0

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();
}
Sjoerd222888
  • 3,228
  • 3
  • 31
  • 64
R.McGuigan
  • 13
  • 5

2 Answers2

1

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.

Catalina Island
  • 7,027
  • 2
  • 23
  • 42
0

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.

NKumar
  • 546
  • 5
  • 14
  • 1
    *"modifying the panel dimensions"* The correct way to do that is to `pack()` the top level container. The programmer should not be trying to guess the size needed (for a cross-platform GUI that is designed using layouts). – Andrew Thompson Sep 01 '17 at 10:07