Having difficulty add a custom icon to a JFrame - java

I have been trying to change the icon in the frame. I have virtually tried everything:
The icon is 16x16 which is the right size ....doesn't work
I've trying PNG,GIF and JPG formats none of them work.
Tried different way of setting the icon....doesn't work.
I've tried relative (local paths) e.g. "icon.gif" and absolute paths e.g. "c:\work\java\icon.gif" ...doesn't work
Here is my code and see if you can figure it out
Thanks
Oli
import javax.swing.*;
public class androidDriver
{
public static void main(String[] args) throws IOException
{
JFrame f = new JFrame("Android Data Viewer");
f.setResizable(false);
f.setSize(300,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setIconImage(new ImageIcon("androidIcon2.gif").getImage());
}
}

If you put the image in the same directory as the class file then the following should work for you:
f.setIconImage(new ImageIcon(androidDriver.class.getResource("androidIcon2.gif")).getImage());
Also would suggest setting the icon image before you make the frame visible
f.setIconImage(new ImageIcon(androidDriver.class.getResource("androidIcon2.gif")).getImage());
f.setVisible(true);

I suspect you may have to actually wait for the image to load using a MediaTracker. It's likely that the image is still loading at the point the frame setIconImage references it, so it does nothing.

Have you tried using Toolkit.getDefaultToolkit().getImage("androidIcon2.gif")
And two other things:
Does the image exist? The code you posted will fail silently.
Is it formatted properly? (though I assume Java could handle it if it wasn't)

Make a separate folder next to the source folder then put your image in there, and then use ImageIO to get the image like so:
f.setIconImage(ImageIO.read(new File("res/androidIcon2.gif")));
Also, if that doesn't work, try saving the image as a .png instead of a .gif.

Related

Custom ToolBar with Java Swing for Desktop

I have created a GUI with Java Swing and wanting to create a custom toolbar according to my modules. Below are the images am wanting to use:
These images are placed in the same level as the src folder within my application. I am aware that I can perhaps create a jar with these images so that I can easily access them from within my application but do not know how. I have spent hours trying to make this work.
Below is my GUI that I have created ad wanting to beautify with these images for the toolbar else create an array of labels that will act as a navigation but either approach I couldn't get it to work.
The code below was my last attempt on this:
JToolBar toolbar1 = new JToolBar();
ImageIcon client = new ImageIcon("clients.png");
ImageIcon timesheet = new ImageIcon("timesheets.png");
JButton clientTB = new JButton(client);
JButton timesheetTB = new JButton(timesheet);
toolbar1.add(clientTB );
toolbar1.add(timesheetTB);
add(toolbar1, BorderLayout.NORTH);
I even moved these images and placed them within the class that's calling them.
What could I be doing wrong, please help?
You have a look at the JavaDocs for ImageIcon(String), the String value is "a String specifying a filename or path"
This is a problem, because your images aren't actually files, any more, they have been embedded within your application (typically within the resulting jar file) and no longer be treated like "normal files".
Instead, you need to use Class#getResource which searches the application's classpath for the named resource, something like...
// This assumes that the images are in the default package
// (or the root of the src directory)
ImageIcon client = new ImageIcon(getClass().getResource("/clients.png"));
Now, I have a personal dislike for ImageIcon, because it won't tell you when the image is loaded for some reason, like it can't be found or it's the wrong format.
Instead, I'd use ImageIO to read the image
ImageIcon client = new ImageIcon(ImageIO.read(getClass().getResource("/clients.png")));
which will do two things, first, it will throw a IOException if the image can't be loaded for some reason and two, it won't return until the image is fully loaded, which is helpful.
See Reading/Loading an Image for more details

Simple Java GUI, cards not appearing

import javax.swing.*;
public class SlideShow {
JFrame slide = new JFrame("Slide Show");
public SlideShow(){
slide.setSize(300,400);
slide.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
slide.setVisible(true);
slide.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel label = new JLabel(new ImageIcon("Images/picture1"));
panel.add(label);
slide.add(panel);
}
public static void main(String[] args){
SlideShow slide = new SlideShow();
}
}
I have to create a simple Java GUI that displays some cards. First, I just wanted to test it by displaying one card. For some reason I can't seem to figure out why nothing is being displayed.
You haven't actually used a proper file name "Images/picture1". Should be something like "Images/picture1.png" with the file format
Also image files, generally should be read from the class path, if you plan on having them embedded to the program. To do so, you will first need to put the file in the class path. With most IDE build configurations it's as simple as placing the image in the src. So
ProjectRoot
src
images
picture1.png
Then you would read it like
new ImageIcon(getClass().getResource("/images/picture1.png"));
A better approach would be to use ImageIO.read(). If the file path is incorrect, it will throw an exception, so you know where you're going wrong
Image image = ImageIO.read(getClass().getResource("/images/picture1.png"));
ImageIcon icon = new ImageIcon(image);
You will need to put it in the try/catch block
Also do what codeNinja said about the setVisible() after adding component. Also preferably pack() the frame, instead of setSize()
You need to set the Frame visible after you add all necessary components to it. Move slide.setVisible(true); Down to the bottom of the constructor like this:
...
slide.add(panel);
slide.setVisible(true);
Alternatively you can add slide.revalidate(); at the bottom of your constructor.

How to change java icon in a JFrame

Ok so I've been researching this one quiet a bit. I am fairly new to java but thought that this one would be easy. Ive tried just about every way that has been answered on this site and still no luck, and usually when I look here I am able to find a answer that fits what I am looking for. Does anyone know how to change the Java icon in the top corner of the JFrame. I'm pretty positive that its not my file path either because all my images are in the same folder and they all work, this is the only one that I can't seem to get to work.
This is the first part my code for the main menu of my program, everything works except when i try to add the icon image. The code I've entered below does not have anything in it for the JFrame IconImage, I removed it since it didn't work. So if there is someone who knows how to get it working with this code that would be highly appreciated, thank you very much in advanced!
public class MainFrame
{
private MyPanel main;
private MyPanel2 create;
private MyPanel3 update;
private MyPanel4 find;
JFrame frame = new JFrame("Main Menu:");
public void displayGUI()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
contentPane.setLayout(new CardLayout());
main = new MyPanel(contentPane, this);
create = new MyPanel2(contentPane);
update = new MyPanel3(contentPane);
find = new MyPanel4(contentPane);
contentPane.add(main, "Main Menu");
contentPane.add(create, "Create Part");
contentPane.add(update, "Update Part");
contentPane.add(find, "Find Part");
frame.setLocation(200, 200);
frame.setSize(700, 580);
frame.setContentPane(contentPane);
frame.setVisible(true);
}
I have an answer for you. First, make sure that the images are in a folder, not a package. Next, insert this line of code:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("path/to/image.png"));
ImageIcon icon = new ImageIcon( );
setIconImage(icon.getImage());
This code gets the image from the class path, and returns it as a image icon, and then it sets it. This should add the image icon to the application. If it doesn't, then tell me.
EDIT: After you told me that that didn't work then I decided to take a second crack at it...
First, put your images into a completely separate folder. I usually call this /res. Next, put your image in there. Now, for loading I took a completely different route. I decided to use ImageIO instead of default loading. To load the image, you use this code:
try {
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
}
catch (IOException exc) {
exc.printStackTrace();
}
ImageIO works a lot better for loading images. If this still doesn't work then please tell me.
If you want to export this as a JAR then put a folder the same name as you used in the program in the same directory as the JAR.
For example in a NetBeans project, create a resources folder in the src folder.
Put your images (jpg, ...) in there.
Whether you use ImageIO or Toolkit (including getResource),
you must include a leading / in your path to the image file:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg"));
setIconImage(image);
If this code is inside your JFrame class, the image is added to the frame as an icon in your title bar.
This works pretty fine for me.
Just add this after you've created your JFrame.
try {
Image image = new ImageIcon("/icons/image.jpg").getImage();
frame.setIconImage(image);
}catch(Exception e){
System.out.println("Application icon not found");
}
Paste your image icon (fav.png) in the same package first,
Write following code in constructor of JFrame:
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("fav.png")));
Note:- fav.png is the name of icon
this.setIconImage(new ImageIcon(getClass().getResource("/iconsfolder/iconsname.jpg")).getImage());
// sets the Global icon for the system
try this code put after this code:
public void displayGUI()
{

JFrame's icon not displaying

I've got a Java application with Swing's JFrame as a main GUI unit. I've set the icon to it via setIconImage(). When I run this program in NetBeans, everything works fine and the frame's icon displays. But when I compile it and try to run jar-file (with JRE7), the application has standard icon with Duke. How do I change that icon when running app outside NetBeans?
UPD:
OK, here's the code:
public static void main(String[] args) throws IOException{
URL imgUrl = Polygon.class.getResource("/imgs/icon.png");
Image img = ImageIO.read(imgUrl);
JFrame f = new JFrame();
f.setSize(new Dimension(500, 500));
f.setIconImage(img);
f.setVisible(true);
}
UPD2:
I've added this line to the end of the code:
JOptionPane.showMessageDialog(null, new ImageIcon(img));
Everything's fine with the image! It loads! BUT it's not displayed as the icon.
When you run the application from inside Netbeans, the files from your project folder are available, but if you run the compiled JAR yourself they may not.
Read this example (note the comments) to load your image properly.
Try getClass().getResource("imgs/icon.png"). It works for me. Note the difference between absolute and relative path. You may not need the leading /.

export a JOGL applet and embedd into a html page

It is some time that I'm testing opengl with java and JOGL. I have a good result and I wan to publish it on the web, but I have a problem. I'm in eclipse, and I'm testing an Applet with JOGL.
EDIT: Thanks to Ricket answer it fixed this problem
first of all i have this run time error (but the program works correctly):
java.lang.IllegalArgumentException:
adding a window to a container at
EDIT: but it still doesn't work:
then I found this incredibly clear page
and I did what is said. I open html with the browser, the libs are downloaded, but it stops at Starting applet AppletHelloWorld, as that is the name I gave to my applet.
Maybe I am missing something like a main function or exporting the jar properly?
This is my main code:
public class AppletHelloWorld extends Applet
{
public static void main(String[] args)
{
JFrame fr=new JFrame();
fr.setBounds(0,0,1015,600);
fr.add(new AppletHelloWorld());
fr.setVisible(true);
}
public void init()
{
setLayout(null);
MyJOGLProject canvas = new MyJOGLProject(); //MyJOGLProject extends JFrame
canvas.run(); // this do setVisible(true)
} //....
Just as the error says, you're trying to add a window to a container. A JFrame is a window. You can't add a JFrame to anything, including a Container. I think perhaps you either don't know what a JFrame is, or don't know what a Container is.
Ideally you would have MyJOGLProject extend GLEventListener instead. Then your init function would make a new GLCanvas, add an instance of MyJOGLProject to it (via addGLEventListener), and then add the GLCanvas to your applet.
Alternatively, if you're okay with the applet popping up a JFrame, then simplify your init method:
public void init() {
setLayout(null);
MyJOGLProject canvas = new MyJOGLProject();
canvas.setVisible(true);
}
That should do it.
Use JApplet. I think that's the reason why it fails.
(Use Webstart with JNLP in NetBeans)

Categories