开发者

Java Combo Boxes + Image Icons

开发者 https://www.devze.com 2023-03-20 10:24 出处:网络
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

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

Java Combo Boxes + Image Icons

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()==ItemE开发者_Python百科vent.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

0

精彩评论

暂无评论...
验证码 换一张
取 消