I just tried to put "user.png" file in Jlabel
, and add it to JFrame
.
("user.png" file exists in the same directory with the Java file)
Also, I think frame setIconImage
also didn't work.
What should I do to fix it?
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;
class TestLabel {
public static void main(String[] args){
ImageIcon image = new ImageIcon("user.png");
JLabel label = new JLabel();
label.setText("This is a point icon");
label.setIcon(image);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
JFrame frame = new JFrame("title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.getContentPane().setBackground(new Color(0x00B890));
frame.setVisible(true);
frame.add(label);
}
}
[edit version]
package basic;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.Taskbar;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
class TestLabel {
public static void main(String[] args){
ImageIcon image = new ImageIcon(new BufferedImage(400,100,BufferedImage.TYPE_INT_RGB));
JLabel label = new JLabel();
label.setText("This is a point icon");
label.setIcon(image);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
JFrame frame = new JFrame("title");
Taskbar taskbar=Taskbar.getTaskbar();
BufferedImage favicon = null;
try{
favicon = ImageIO.read(TestLabel.class.getResource("user.png"));
}
catch (IOException e){
System.out.println("IOException occured");
}
taskbar.setIconImage(favicon);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.getContentPane().setBackground(new Color(0x00B890));
frame.add(label);
frame.pack();
frame.setVisible(true);
}
}
This is the execution result:
