Copy and Paste any Image file into your current project folder and use getClass() method to get reference of current folder then use its getResource() method to lookup the image file.
It returns a type of URL class from java.net package.
Load the image into memory using ImageIcon class
Now use setIconImage() method to set the Icon image
Example
import javax.swing.*;
import java.net.*;
public class MyWindow extends JFrame
{
public MyWindow()
{
URL iconURL = getClass().getResource("icon.jpg");
ImageIcon icon = new ImageIcon(iconURL);
setIconImage(icon.getImage());
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new MyWindow();
}
}
It returns a type of URL class from java.net package.
Load the image into memory using ImageIcon class
Now use setIconImage() method to set the Icon image
Example
import javax.swing.*;
import java.net.*;
public class MyWindow extends JFrame
{
public MyWindow()
{
URL iconURL = getClass().getResource("icon.jpg");
ImageIcon icon = new ImageIcon(iconURL);
setIconImage(icon.getImage());
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new MyWindow();
}
}
No comments:
Post a Comment