Java Combo Boxes + Image Icons - java

I'm trying to build a really basic program that will alternate between two pictures depending on which item from a dropdown box is selected. This is the code I'm trying to run, but I keep getting an error saying:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:181)
at Gui.<init>(Gui.java:10)
at Apples.main(Apples.java:7)
The images are in the src file.
Does anyone know what I am doing wrong??
Thanks,
Ravin
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gui extends JFrame{
private JComboBox box;
private JLabel picture;
private static String [] filename = {"Ravinsface.png", "Wojs face.png"};
private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0])), new ImageIcon(getClass().getResource(filename[1]))};
public Gui(){
super("The Title");
setLayout(new FlowLayout());
box = new JComboBox(filename);
box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event){
if(event.getStateChange()==ItemEvent.SELECTED);
picture.setIcon(pics[box.getSelectedIndex()]);
}
}
);
add(box);
picture = new JLabel(pics[1]);
add(picture);
}
}

Use getClass().getClassLoader().getResource(String)
/e1 I put an explanation of the different getResource(String) methods on the other answer.

It looks like one (or more) of the arguments you are passing into your ImageIcon constructor are null. This is because the resource is not being found here:
private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0])), new ImageIcon(getClass().getResource(filename[1]))};
Why aren't you just using
new ImageIcon(String filename)
? I'm not 100% sure how getResource works, never having used it.

do this:
you must put your .png
beside your .class files
(in project_name/bin)
then your files path can recognize
then it will works
remember you are using class loader so if you put images beside .class files it will be correct

Related

Exception in thread "main" java.lang.NullPointerException when make a JLabel [duplicate]

This question already has answers here:
Java - class.getResource returns null
(21 answers)
Closed 5 years ago.
I'am a beginner and I've met some problems when I attempted to use a JPG to make a label.
and it shows that
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.(Unknown Source)
at pane.MyImageIcon.(MyImageIcon.java:11)
at pane.MyImageIcon.main(MyImageIcon.java:21)
package pane;
import java.net.*;
import java.awt.*;
import javax.swing.*;
public class MyImageIcon extends JFrame {
public MyImageIcon() {
JFrame jf=new JFrame();
Container container = jf.getContentPane();
JLabel jl = new JLabel("it is a frame", JLabel.CENTER);
URL url = MyImageIcon.class.getResource("ofii.jpg");
Icon icon = new ImageIcon(url);
jl.setIcon(icon);
jl.setHorizontalAlignment(SwingConstants.CENTER);
jl.setOpaque(true);
container.add(jl);
jf.setSize(800,800);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
new MyImageIcon();
}
}
Print out variable "url". You will find it being null. Check if the image actually exists in the jar, on the given path. These posts might help:
Getting images from a .jar file
Jar get image as resource
https://gamedev.stackexchange.com/questions/30416/dynamically-load-images-inside-jar
Unknown source usually means it can't find the image, Make sure the image exists and is placed in the same location as your Java class file, if not, you can use classpath relative paths in getResource() putting / at the start

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?
There are two likely problems here:
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).
The code is trying to load an application resource as a file, when it will likely be (or become) an embedded-resource that should be accessed by URL. See the embedded resource info. page for tips on how to form the URL.

How to convert SWT Image to data URI for use in Browser-widget

I am trying to display images inside a Browser-widget (SWT). These images can be found inside the a jar file (plug-in development). However: this is not directly possible as the browser-widget expects some kind of URL or URI information.
My idea is to turn SWT-images into data-URI values, which I could induce into the src-attribute of every given img-element. I know, that this is not a good solution from a performance point of view, but I don't mind the speed disadvantage.
I'd like to know how to turn a SWT image into a data-URI value for use in a browser-widget.
My code so far:
package editor.plugin.editors.htmlprevieweditor;
import editor.plugin.Activator;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
public class HtmlPreview extends Composite implements DisposeListener {
private final Browser content;
public HtmlPreview(final Composite parent, final int style) {
super(parent, style);
this.setLayout(new FillLayout());
content = new Browser(this, style);
final ImageData imageData = Activator.getImageDescriptor(Activator.IMAGE_ID + Activator.PREVIEW_SMALL_ID).getImageData();
content.setText("<html><body><img src=\"data:image/png;base64," + imageData + "\"/></body></html>"); // need help on changing imageData to a base64-encoded String of bytes?
this.addDisposeListener(this);
}
#Override
public void widgetDisposed(final DisposeEvent e) {
e.widget.dispose();
}
}
Any help is greatly appreciated :)!
Edit 1: I have read SWT Image to/from String , but unfortunately it does not seem to exactly cover my needs.
Edit 2: I don't know if it matters, but I am trying to load a PNG24-image with per-pixel alpha-transparency.
The question is too general if you only say "Browser in SWT". Mozzila browser supports jar URL protocol, and you can do this:
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final URL url = ShellSnippet.class.getResource("/icons/full/message_error.gif");
final Browser browser = new Browser(shell, SWT.MOZILLA);
final String html = String.format("<html><head/><body>image: <img src=\"%s\"/></body></html>", url);
browser.setText(html);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
It looks like this:
I used an image from the JFace jar to keep the snippet simple and yet work for most people out of the box. It is GIF, but I expect it to work just as well with PNG files.
If you use Internet Explorer, something I do not recommend because your application depends on OS version, this does not work. It looks like this (after changing in the snippet the style from SWT.MOZILLA to SWT.NONE):
It does however understand the file protocol and you can copy files to the temp folder and create URLs directly to the file using File.toURL(). This should work for any browser.
I cannot test the simple solution on WEBKIT broswer. If anyone can, please post the result in a comment.

How to set Icon to JFrame

I tried this way, but it didnt changed?
ImageIcon icon = new ImageIcon("C:\\Documents and Settings\\Desktop\\favicon(1).ico");
frame.setIconImage(icon.getImage());
Better use a .png file; .ico is Windows specific. And better to not use a file, but a class resource (can be packed in the jar of the application).
URL iconURL = getClass().getResource("/some/package/favicon.png");
// iconURL is null when not found
ImageIcon icon = new ImageIcon(iconURL);
frame.setIconImage(icon.getImage());
Though you might even think of using setIconImages for the icon in several sizes.
Try putting your images in a separate folder outside of your src folder. Then, use ImageIO to load your images. It should look like this:
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
Finally I found the main issue in setting the jframe icon. Here is my code. It is similar to other codes but here are few things to mind the game.
this.setIconImage(new ImageIcon(getClass().getResource("Icon.png")).getImage());
1) Put this code in jframe WindowOpened event
2) Put Image in main folder where all of your form and java files are created e.g.
src\ myproject\ myFrame.form
src\ myproject\ myFrame.java
src\ myproject\ OtherFrame.form
src\ myproject\ OtherFrame.java
src\ myproject\ Icon.png
3) And most important that name of file is case sensitive that is icon.png won't work but Icon.png.
this way your icon will be there even after finally building your project.
This works for me.
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(".\\res\\icon.png"));
For the export jar file, you need to configure the build path to include the res folder and use the following codes.
URL url = Main.class.getResource("/icon.png");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(url));
Yon can try following way,
myFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
Here is the code I use to set the Icon of a JFrame
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
try{
setIconImage(ImageIO.read(new File("res/images/icons/appIcon_Black.png")));
}
catch (IOException e){
e.printStackTrace();
}
Just copy these few lines of code in your code and replace "imgURL" with Image(you want to set as jframe icon) location.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create the frame.
JFrame frame = new JFrame("A window");
//Set the frame icon to an image loaded from a file.
frame.setIconImage(new ImageIcon(imgURL).getImage());
I'm using the following utility class to set the icon for JFrame and JDialog instances:
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;
public class WindowUtilities
{
public static void setIconImage(Window window)
{
window.setIconImage(Toolkit.getDefaultToolkit().getImage(WindowUtilities.class.getResource("/Icon.jpg")));
}
public static String resourceToString(String filePath) throws IOException, URISyntaxException
{
InputStream inputStream = WindowUtilities.class.getClassLoader().getResourceAsStream(filePath);
return toString(inputStream);
}
// http://stackoverflow.com/a/5445161/3764804
private static String toString(InputStream inputStream)
{
try (Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A"))
{
return scanner.hasNext() ? scanner.next() : "";
}
}
}
So using this becomes as simple as calling
WindowUtilities.setIconImage(this);
somewhere inside your class extending a JFrame.
The Icon.jpg has to be located in myproject\src\main\resources when using Maven for instance.
I use Maven and have the structure of the project, which was created by entering the command:
mvn archetype:generate
The required file icon.png must be put in the src/main/resources folder of your maven project.
Then you can use the next lines inside your project:
ImageIcon img = new ImageIcon(getClass().getClassLoader().getResource("./icon.png"));
setIconImage(img.getImage());
My project code is as below:
private void setIcon() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/slip/images/cage_settings.png")));
}
frame.setIconImage(new ImageIcon(URL).getImage());
/*
frame is JFrame
setIcon method, set a new icon at your frame
new ImageIcon make a new instance of class (so you can get a new icon from the url that you give)
at last getImage returns the icon you need
it is a "fast" way to make an icon, for me it is helpful because it is one line of code
*/
public FaceDetection() {
initComponents();
//Adding Frame Icon
try {
this.setIconImage(ImageIO.read(new File("WASP.png")));
} catch (IOException ex) {
Logger.getLogger(FaceDetection.class.getName()).log(Level.SEVERE, null, ex);
}
}'
this works for me.

Drag and Drop file path to Java Swing JTextField

Using this question, I created the class below, which handles drag and drop of files to a JTextField. The point of the application is to be able to drag a file into the text field, and have the text field's text set to the file's path (you can see the goal in the code pretty clearly).
My problem is the below code does not compile. The compilation error states Cannot refer to non-final variable myPanel inside an inner class defined in a different method. I haven't worked much with inner classes, so can seomeone show me how to resolve the error and get the code to behave as designed?
Code:
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.io.File;
import java.util.List;
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JTextArea myPanel = new JTextArea();
myPanel.setDropTarget(new DropTarget() {
public synchronized void drop(DropTargetDropEvent evt) {
try {
evt.acceptDrop(DnDConstants.ACTION_COPY);
List<File> droppedFiles = (List<File>) evt
.getTransferable().getTransferData(
DataFlavor.javaFileListFlavor);
for (File file : droppedFiles) {
/*
* NOTE:
* When I change this to a println,
* it prints the correct path
*/
myPanel.setText(file.getAbsolutePath());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
JFrame frame = new JFrame();
frame.add(myPanel);
frame.setVisible(true);
}
}
As the error message says, myPanel needs to be defined as final.
final JTextArea myPanel = new JTextArea();
This way the inner class can be given one reference pointer to the variable instance without concern that the variable might be changed to point to something else later during execution.
Another option is to declare the variable static.
static JTextArea myPanel = new JTextArea();

Categories

Resources