简体   繁体   English

Java Swing图标未出现

[英]Java Swing Icon not appearing

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. 我知道肯定已经超过了if / else语句,所以我真的不知道出了什么问题。

 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();
}

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. 通过修改面板尺寸并在其中放置笑脸进行检查。

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 . 取而代之的是,您可以一次添加标签,然后像显示在此处一样调用setIcon()

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. 根据您的布局,在pack()窗口之前,可能需要更改标签的首选大小或添加一个空标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM