just-max
just-max

Reputation: 171

Using an icon image for a GUI

I have created the following code for a school project, a "password protector", just for fun, really. However, the problem I have is that the icon image does not appear, but instead the default java "coffee cup".

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class UserInterfaceGUI extends JFrame
{
    private static final long serialVersionUID = 1;
    private JLabel userNameInfo; // ... more unimportant vars.

    public UserInterfaceGUI()
    {
        this.setLayout(new FlowLayout());
        userNameInfo = new JLabel("Enter Username:"); // ... more unimportant var. declartions

        this.add(userNameInfo); // ... more unimportant ".add"s

        event e = new event();
        submit.addActionListener(e);
    }

    public static void main(String[] args)
    {
        //This icon has a problem \/
        ImageIcon img = new ImageIcon("[File Location hidden for privacy]/icon.ico");

        UserInterfaceGUI gui = new UserInterfaceGUI();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(400, 140);
        gui.setIconImage(img.getImage());
        gui.setTitle("Password Protector");
        gui.setVisible(true);
    }
}

Can someone tell me why this just shows the java coffee cup at the bottom of the screen and on the bar at the top of the window?

Upvotes: 0

Views: 692

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168815

There are two likely problems here:

  1. Java is unlikely to support .ico files. The only types that can be relied on are GIF, PNG & JPEG.

    For all types supported on any specific JRE, use ImageIO.getReaderFileSuffixes() (but seriously, for app. icons stick to the 3 types with guaranteed support).
  2. The code is trying to load an application resource as a file, when it will likely be (or become) an that should be accessed by URL. See the embedded resource info. page for tips on how to form the URL.

Upvotes: 3

Related Questions