Reputation: 141
I've been trying to set up a window in Netbean's GUI builder, without success. I've tried accessing the JFrame, from my main class as:
public void run(){
JFrame frame = new JFrame("Title of Frame");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("org/icon.png"));
}
Which creates a new frame apart from my main window with my icon.png. I'd like to know if there is some way to gain access to the JFrame that contains the rest of my UI elements, and set that icon.
I've also tried
new SearchAppUI().setIconImage(null);
which doesn't do anything of note.
Setting the icon directly:
JFrame.setIconImage("org/icon.png");
gives me the error, non-static method setIconImage(java.awt.Image) cannot be referenced from a static context.
Is there any way to set the main JFrame's icon from either Netbean's swing desinger preview, or from my run() method?
Upvotes: 3
Views: 51513
Reputation: 71
The OP is a bit dated but just for the record, try this:
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("org/icon.png")));
Upvotes: 7
Reputation: 141
NVM, I found a solution on: http://www.youtube.com/watch?v=o_35iro4b7M
Describing how to set the icon and title of a jFrame. Basically, it requires the libraries
import javax.swing.JFrame;
import java.awt.image.BufferedImage;
import java.io.File;
import java.awt.Image;
import javax.imageio.ImageIO;
I pretty much wanted to stick with using Netbean's guibuilder for now, at least for prototyping.
Upvotes: 3
Reputation: 2483
First of all. It's worth to read How to Make Frames.
You can use the following example.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class FrameWithIcon extends JFrame {
public static void main(String[] args) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
FrameWithIcon myFrame = new FrameWithIcon();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setTitle("Frame with Icon");
myFrame.setLayout(new BorderLayout());
myFrame.setIconImage(
loadImageIcon("org/icon.png").getImage());
Dimension size = new Dimension(250, 100);
JPanel panel = new JPanel();
panel.setPreferredSize(size);
myFrame.add(panel, BorderLayout.LINE_START);
myFrame.setVisible(true);
myFrame.pack();
}
});
} catch (InterruptedException ex) {
} catch (InvocationTargetException ex) {
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
private static ImageIcon loadImageIcon(String path) {
URL imgURL = FrameWithIcon.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
Upvotes: 1