Noah Cagle
Noah Cagle

Reputation: 146

Making a custom icon for a JFrame

Well I was wondering if I could make an icon image for a JFrame. I do know its posible, because, let me say, I am NOT digging the java logo.

Well if I just hava to use a Frame object I will.

Can someone tell me, I know its possible!

Upvotes: 3

Views: 2560

Answers (3)

David Archanjo
David Archanjo

Reputation: 101

You can do the following.

    public Test {
   public static void main(String[] args) {
     JFrame frame = new JFrame("My Frame");
     frame.setIconImage(new ImageIcon(Test.class.getResource("image.png"));
     frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);                                                  
     frame.setVisible(true);
     frame.setSize(100, 100);               

     //other stuffs....
   }  
}

Upvotes: 1

Jeremy Johnson
Jeremy Johnson

Reputation: 469

First, you have to have an image file on your computer. It can be named anything. For this example, we will call this one "pic.jpg". Next, you need to include it in the files that your application is using. For example, if you're using NetBeans, you simply click on "Files" in the left hand side of the IDE (not File as in the menu, mind you). Drag the picture's file over to the folder that houses the main package. This will include it for available use in the code. Inside the method where you define the JFrame, you can create an image like this:

Image frameImage = new ImageIcon("pic.jpg").getImage();

You can now set it as the IconImage for the frame like this:

JFrame frame = new JFrame("Title");
frame.setIconImage(frameImage);

Hope that's helpful.

Note: the reason that the Image object has to be created like this is because Image is abstract and cannot be instantiated by saying new Image();

Props to you, btw, kid. I wish I would have started learning programming when I was your age. Keep at it!

Upvotes: 2

James Williams
James Williams

Reputation: 678

Use an ImageIcon.

ImageIcon icon = new ImageIcon( pathToIcon );
yourFrame.setIconImage(icon.getImage());

Good Luck!

Upvotes: 4

Related Questions