Can someone tell me where is it picking images from? - java

package demo;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*`enter code here`
* ComboBoxDemo.java uses these additional files:`enter code here`
* images/Bird.gif
* images/Cat.gif
* images/Dog.gif
* images/Rabbit.gif
* images/Pig.gif
*/
public class Demo extends JPanel
implements ActionListener {
JLabel picture;
#SuppressWarnings({ "rawtypes", "unchecked" })
public Demo() {
super(new BorderLayout());
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
//Create the combo box, select the item at index 4.
//Indices start at 0, so 4 specifies the pig.
JComboBox petList = new JComboBox(petStrings);
petList.setSelectedIndex(4);
petList.addActionListener(this);
//Set up the picture.
picture = new JLabel();
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
updateLabel(petStrings[petList.getSelectedIndex()]);
picture.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
//The preferred size is hard-coded to be the width of the
//widest image and the height of the tallest image + the border.
//A real program would compute this.
picture.setPreferredSize(new Dimension(177, 122+10));
//Lay out the demo.
add(petList, BorderLayout.PAGE_START);
add(picture, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
/** Listens to the combo box. */
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
updateLabel(petName);
}
protected void updateLabel(String name) {
ImageIcon icon = createImageIcon("images/" + name + ".png");
picture.setIcon(icon);
picture.setToolTipText("A drawing of a " + name.toLowerCase());
if (icon != null) {
picture.setText(null);
} else {
picture.setText("Image not found");
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Demo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ComboBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Demo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
This is the code i have got from oracle but i don't know where it would need to pick images from because every time i create a source folder with images, it still wouldn't pick it up. Or if you could tell me which part of the code is picking the image up? I need to use same kinda code for my work.

ImageIcon icon = createImageIcon("images/" + name + ".png");
This line is providing image path which is images/name.png and value of name could be among these {"Bird", "Cat", "Dog", "Rabbit", "Pig"}
picture.setIcon(icon);
The above line is setting the icon to JLabel picture.
Create a folder named images in root directory of the project and put all .png images in images folder.

If you want to debug where the program fetches the files, you could use the following creating a File object and requesting it's absolute path.
Ideone
System.out.println(new File("images/Bird.png").getAbsolutePath()); // C:\... or /...

See: http://www.thinkplexx.com/learn/howto/java/system/java-resource-loading-explained-absolute-and-relative-names-difference-between-classloader-and-class-resource-loading
I finally found out where the problem lies, but I cannot understand why they way Oracle made the code doesn't work.
Go back to the original code published at
https://www.codetantra.com/java/jdk6.0/tutorial/uiswing/examples/components/ComboBoxDemoProject/src/components/ComboBoxDemo.java
You need to go to the folder where your project is. You will see:
bin
images
src
The images folder may have all the expected image files in it, but the program does not get to them somehow. Copy the gif files into the folder that holds bin, images, and src.
You will now see:
bin
images
src
Bird.gif
Cat.gif
and so forth.
Now go back and change Oracle's code:
// ImageIcon icon = createImageIcon("images/" + name + ".gif"); //This way does not work.
to
ImageIcon icon = createImageIcon(name + ".gif");

Create a folder named images in the same folder where your Demo.java is. And place your images there. The image names, according to your code, are "Bird.png", "Cat.png", "Dog.png", "Rabbit.png", "Pig.png".
So your project structure is something like this:
demo
src
└───demo
│ Demo.java
└───images
Bird.png
Cat.png
Dog.png
Rabbit.png
Pig.png

Related

Java JFrame ImageIcon Issue - JFrame.super.setIconImage() Says image Equals Empty String

I'm working on a game with a small team and they've opened a ticket to change the IconImage, which takes in an ImageIcon object.
I create an ImageIcon object with a java.net.URL pointing to the file location in the CLASSPATH. Then I create an Image object out of ImageIcon.getImage().
Later on in the program, I pass the Image object mentioned above to jframe.setIconImage();
If I run the program in debug, I can see the path to the image is correct, reflecting it's place in the CLASSPATH, but the icon doesn't change. If I step into jframe.setIconImage(), I get to a point where JFrame.java is calling JFrame.super.setIconImage(), but the value of image being passed to the super class is "" (empty string).
I have code in the main class, src folder structure, out/bin folder structure, and a picture of the value being passed as empty string.
Any advise at all is much appreciated and thanks in advance for your time.
==Code==
package orsc;
import orsc.Config;
import javax.swing.*;
import java.applet.Applet;
import java.awt.*;
import java.io.File;
public class ORSCFrame extends ORSCApplet {
private static final long serialVersionUID = 1L;
public String getCacheLocation() {
return Config.F_CACHE_DIR + File.separator;
}
public static void main(String[] args) {
JFrame jframe = new JFrame(Config.SERVER_NAME);
ImageIcon orscIcon = new ImageIcon(ORSCFrame.class.getResource("icon.png"));
Image orscIconImage = orscIcon.getImage();
final Applet applet = new ORSCFrame();
applet.setPreferredSize(new Dimension(512, 334 + 12));
jframe.getContentPane().setLayout(new BorderLayout());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.getContentPane().add(applet);
jframe.setResizable(true);
jframe.setVisible(true);
// jframe.setAlwaysOnTop(true);
jframe.setBackground(Color.black);
jframe.setMinimumSize(new Dimension(512, 334 + 12));
jframe.setIconImage(orscIconImage);
jframe.pack();
jframe.setLocationRelativeTo(null);
applet.init();
applet.start();
// jframe.add(applet);
}
#Override
public void playSound(byte[] soundData, int offset, int dataLength) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void stopSoundPlayer() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
== src folder ==
==out/bin folder ==
==step into line 33 (jframe.setIconImage(orscIconImage);) ==
==pic of jframe ==

Java Swing error Exception in thread “AWT-EventQueue-0” java.lang.IllegalArgumentException: input == null [duplicate]

I am having a error for my GUI. Trying to set title bar icon then be included in a Runnable JAR.
BufferedImage image = null;
try {
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
}
catch (IOException e) {
e.printStackTrace();
}
frame.setIconImage(image);
Here is the error I am getting:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at GUI.<init>(GUI.java:39)
at GUI.main(GUI.java:351)
The image is in the correct directory which "resources" folder is the root of the
project file
First of all, change this line :
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
to this :
image = ImageIO.read(getClass().getResource("/resources/icon.gif"));
More info, on as to where lies the difference between the two approaches, can be found on this thread - Different ways of loading a Resource
For Eclipse:
How to add Images to your Resource Folder in the Project
For NetBeans:
Handling Images in a Java GUI Application
How to add Images to the Project
For IntelliJ IDEA:
Right-Click the src Folder of the Project. Select New -> Package
Under New Package Dialog, type name of the package, say resources. Click OK
Right Click resources package. Select New -> Package
Under New Package Dialog, type name of the package, say images. Click OK
Now select the image that you want to add to the project, copy it. Right click resources.images package, inside the IDE, and select Paste
Use the last link to check how to access this file now in Java code. Though for this example, one would be using
getClass().getResource("/resources/images/myImage.imageExtension");
Press Shift + F10, to make and run the project. The resources and images folders, will be created automatically inside the out folder.
If you are doing it manually :
How to add Images to your Project
How to Use Icons
A Little extra clarification, as given in this answer's first
code example.
QUICK REFERENCE CODE EXAMPLE(though for more detail consider, A little extra clarification link):
package swingtest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 7/1/14
* Time: 9:44 AM
* To change this template use File | Settings | File Templates.
*/
public class ImageExample {
private MyPanel contentPane;
private void displayGUI() {
JFrame frame = new JFrame("Image Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new MyPanel();
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class MyPanel extends JPanel {
private BufferedImage image;
public MyPanel() {
try {
image = ImageIO.read(MyPanel.class.getResource("/resources/images/planetbackground.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return image == null ? new Dimension(400, 300): new Dimension(image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new ImageExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
There's a much easier way to load and set an image as a frame icon:
frame.setIconImage(
new ImageIcon(getClass().getResource("/resources/icon.gif")).getImage());
And thats all :)! You don't even have to use a try-catch block because ImageIcon does not throw any declared exceptions. And due to getClass().getResource(), it works both from file system and from a jar depending how you run your application.
If you need to check whether the image is available, you can check if the URL returned by getResource() is null:
URL url = getClass().getResource("/resources/icon.gif");
if (url == null)
System.out.println( "Could not find image!" );
else
frame.setIconImage(new ImageIcon(url).getImage());
The image files must be in the directory resources/ in your JAR, as shown in How to Use Icons and this example for the directory named images/.

Adding links to options in a Input Dialog

I'm trying to add links into a project that i'm making in eclipse. I have researched on how to do it, but i can't find much on it that pertains to eclipse.
This is the code that im trying to add links too:
Object[] possibilities = {"" +
"AWS Welder Certification Testing",
"Computer science",
"Aviation", "Construction",
"Health science",
"Programming",
"3D design",
"Cyber security",
"Advanced Safety Certification",
"Healthcare Provider CPR",
"Dietary Manager",
"Insurance",
"Emergency 911 Operator",
"Job Safety Analysis",
"Real Estate",
"Pharmacy Technician",
"Special Needs Education",
"School Bus Driver Training",
"Phlebotomy Technician",
"Security Guard",
"Home Inspection",
"Court Reporter",
"Long Term Care/Nurse Aide (CNA)",
"EPA Lead Safe Renovator Certification",};
Component frame = null;
Icon icon = null;
String s = (String)JOptionPane.showInputDialog(
frame,
"What class might you want to attend?\n"
+ "\"The options are endless!\"",
"Class Options",
JOptionPane.PLAIN_MESSAGE,
icon,
possibilities,
"all");
When I run the program, a dialog box appears, and it gives all the options of classes above. How would I make it to where when the user clicks on a class it will link them to the website for that class?
I recommend using a JTextField rather than a JButton for this use.
E.G.
That is how it appears when the mouse is hovering over the first link.
LinkLabel.java
/* License - LGPL
LinkLabel Using the Desktop Class
There are a lot of link labels. This one uses the Java 1.6+
Desktop class for its functionality, and is thereby suitable
for applets, applications launched using JWS, and 'standard'
(non-JWS) desktop applications.
*/
import java.awt.Desktop;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.border.MatteBorder;
import javax.swing.border.Border;
import java.net.URI;
import java.io.File;
/**
A Java 1.6+ LinkLabel that uses the Desktop class for opening
the document of interest.
The Desktop.browse(URI) method can be invoked from applications,
applets and apps. launched using Java Webstart. In the latter
two cases, the usual fall-back methods are used for sandboxed apps
(see the JavaDocs for further details).
While called a 'label', this class actually extends JTextField,
to easily allow the component to become focusable using keyboard
navigation.
To successfully browse to a URI for a local File, the file name
must be constructed using a canonical path.
#author Andrew Thompson
#version 2008/08/23
*/
public class LinkLabel
// we extend a JTextField, to get a focusable component
extends JTextField
implements MouseListener, FocusListener, ActionListener {
/** The target or href of this link. */
private URI target;
public Color standardColor = new Color(0,0,255);
public Color hoverColor = new Color(255,0,0);
public Color activeColor = new Color(128,0,128);
public Color transparent = new Color(0,0,0,0);
public boolean underlineVisible = true;
private Border activeBorder;
private Border hoverBorder;
private Border standardBorder;
/** Construct a LinkLabel that points to the given target.
The URI will be used as the link text.*/
public LinkLabel(URI target) {
this( target, target.toString() );
}
/** Construct a LinkLabel that points to the given target,
and displays the text to the user. */
public LinkLabel(URI target, String text) {
super(text);
this.target = target;
}
/* Set the active color for this link (default is purple). */
public void setActiveColor(Color active) {
activeColor = active;
}
/* Set the hover/focused color for this link (default is red). */
public void setHoverColor(Color hover) {
hoverColor = hover;
}
/* Set the standard (non-focused, non-active) color for this
link (default is blue). */
public void setStandardColor(Color standard) {
standardColor = standard;
}
/** Determines whether the */
public void setUnderlineVisible(boolean underlineVisible) {
this.underlineVisible = underlineVisible;
}
/* Add the listeners, configure the field to look and act
like a link. */
public void init() {
this.addMouseListener(this);
this.addFocusListener(this);
this.addActionListener(this);
setToolTipText(target.toString());
if (underlineVisible) {
activeBorder = new MatteBorder(0,0,1,0,activeColor);
hoverBorder = new MatteBorder(0,0,1,0,hoverColor);
standardBorder = new MatteBorder(0,0,1,0,transparent);
} else {
activeBorder = new MatteBorder(0,0,0,0,activeColor);
hoverBorder = new MatteBorder(0,0,0,0,hoverColor);
standardBorder = new MatteBorder(0,0,0,0,transparent);
}
// make it appear like a label/link
setEditable(false);
setForeground(standardColor);
setBorder(standardBorder);
setCursor( new Cursor(Cursor.HAND_CURSOR) );
}
/** Browse to the target URI using the Desktop.browse(URI)
method. For visual indication, change to the active color
at method start, and return to the standard color once complete.
This is usually so fast that the active color does not appear,
but it will take longer if there is a problem finding/loading
the browser or URI (e.g. for a File). */
public void browse() {
setForeground(activeColor);
setBorder(activeBorder);
try {
Desktop.getDesktop().browse(target);
} catch(Exception e) {
e.printStackTrace();
}
setForeground(standardColor);
setBorder(standardBorder);
}
/** Browse to the target. */
public void actionPerformed(ActionEvent ae) {
browse();
}
/** Browse to the target. */
public void mouseClicked(MouseEvent me) {
browse();
}
/** Set the color to the hover color. */
public void mouseEntered(MouseEvent me) {
setForeground(hoverColor);
setBorder(hoverBorder);
}
/** Set the color to the standard color. */
public void mouseExited(MouseEvent me) {
setForeground(standardColor);
setBorder(standardBorder);
}
public void mouseReleased(MouseEvent me) {}
public void mousePressed(MouseEvent me) {}
/** Set the color to the standard color. */
public void focusLost(FocusEvent fe) {
setForeground(standardColor);
setBorder(standardBorder);
}
/** Set the color to the hover color. */
public void focusGained(FocusEvent fe) {
setForeground(hoverColor);
setBorder(hoverBorder);
}
public static void main(String[] args) throws Exception {
JPanel p = new JPanel(new GridLayout(0,1));
File f = new File(".","LinkLabel.java");
/* Filename must be constructed with a canonical path in
order to successfully use Desktop.browse(URI)! */
f = new File(f.getCanonicalPath());
URI uriFile = f.toURI();
LinkLabel linkLabelFile = new LinkLabel(uriFile);
linkLabelFile.init();
p.add(linkLabelFile);
LinkLabel linkLabelWeb = new LinkLabel(
new URI("http://pscode.org/sscce.html"),
"SSCCE");
linkLabelWeb.setStandardColor(new Color(0,128,0));
linkLabelWeb.setHoverColor(new Color(222,128,0));
linkLabelWeb.init();
/* This shows a quirk of the LinkLabel class, the
size of the text field needs to be constrained to
get the underline to appear properly. */
p.add(linkLabelWeb);
LinkLabel linkLabelConstrain = new LinkLabel(
new URI("http://sdnshare.sun.com/"),
"SDN Share");
linkLabelConstrain.init();
/* ..and this shows one way to constrain the size
(appropriate for this layout).
Similar tricks can be used to ensure the underline does
not drop too far *below* the link (think BorderLayout
NORTH/SOUTH).
The same technique can also be nested further to produce
a NORTH+EAST packing (for example). */
JPanel labelConstrain = new JPanel(new BorderLayout());
labelConstrain.add( linkLabelConstrain, BorderLayout.EAST );
p.add(labelConstrain);
LinkLabel linkLabelNoUnderline = new LinkLabel(
new URI("http://java.net/"),
"java.net");
// another way to deal with the underline is to remove it
linkLabelNoUnderline.setUnderlineVisible(false);
// we can use the methods inherited from JTextField
linkLabelNoUnderline.
setHorizontalAlignment(JTextField.CENTER);
linkLabelNoUnderline.init();
p.add(linkLabelNoUnderline);
JOptionPane.showMessageDialog( null, p );
}
}

Change jLabel icon

It seems like i'm not the only one with that question but I can't find an answer that solves the problem.
I created a Label and assign an Icon to it using WYSIWYG interface designer.
Now I want to change the icon dynamically during runtime.
The logic way would be like this (my first attempt) :
ImageIcon newIcon = new ImageIcon("SomePath");
jLabel1.setIcon(newIcon);
When I do this the Icon simply disapears from the interface so I googled it and someone said to "flush" the icon whatever this means I tried it :
ImageIcon newIcon = new ImageIcon("SomePath");
newIcon.getImage().flush();
jLabel1.setIcon(newIcon);
Still having the same problem.. The icon disapears.
What am I doing wrong ?
Update (Full Method) :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
attempted = myEngine.Attempt('q', word);
if(attempted)
{
this.jTextArea1.setText(myEngine.ChangeEncrypt('q', word, this.jTextArea1.getText()));
}
else
{
JOptionPane.showMessageDialog(null,"The Letter Q is not in the word", "Error",JOptionPane.WARNING_MESSAGE);
jButton1.setEnabled(false);
life ++;
ImageIcon newIcon = myEngine.UpdatePicture(life);
newIcon.getImage().flush();
jLabel1.setIcon(newIcon);
}
This is the UpdatePicture Method :
public ImageIcon UpdatePicture(int life)
{
ImageIcon emptyIcon = new ImageIcon();
if (life == 0)
{
ImageIcon iconZero = new ImageIcon("/hang0.gif");
return iconZero;
}
if (life == 1)
{
ImageIcon iconOne = new ImageIcon("/hang1.gif");
return iconOne;
}
if (life == 2)
{
ImageIcon iconTwo = new ImageIcon("/hang2.gif");
return iconTwo;
}
if (life == 3)
{
ImageIcon iconThree = new ImageIcon("/hang3.gif");
return iconThree;
}
if (life == 4)
{
ImageIcon iconFour = new ImageIcon("/hang4.gif");
return iconFour;
}
if (life == 5)
{
ImageIcon iconFive = new ImageIcon("/hang5.gif");
return iconFive;
}
if (life == 6)
{
ImageIcon iconSix = new ImageIcon("/hang6.gif");
return iconSix;
}
return emptyIcon;
}
Not sure the whole code was necessary but still it might help.
The life variable starts at 0.
I checked and in the UpdatePicture it hits the "/hang1.gif"; and returns it.
If the file is in your src folder then :
ImageIcon ii = new ImageIcon(getClass().getResource("/myFile.gif"));
You really should not put that slash before the name of your icon. It works like that.
I know this is an old question thread, but was having a hell of a time getting a icon replaced on a jLabel when my app was running. This is what finally fixed it:
I created a new folder in the source package named images and put the images in there.
In my Frame (main class) I added this below the initComponents method:
private void moreComponents() {
// get images for initial screen prompts (Skd2_startPanel, loading label1).
// StartPanel is a panel on the Frame that has the loading label on it))
try {
lcImage= new ImageIcon(ImageIO.read(getClass().getResource("/images/LC.png")));
clImage= new ImageIcon(ImageIO.read(getClass().getResource("/images/CL.png")));
} catch (IOException ex) {
Logger.getLogger(Skd2_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
LC and CL.png are the images I want as the label icons.
In a different class I added the following when I wanted the icon to change:
loadingLabel1.setIcon(lcImage); // or clImage as needed.
You'll need the following imports:
import java.util.logging.Logger;
import javax.imageio.ImageIO;
And add these two declarations just below the variables declarations:
static ImageIcon lcImage;
static ImageIcon clImage;
Hope this helps someone searching the web for an answer.

Don't know what's wrong with my code. Java GUI

I'm trying to make a combo box that pops up with an image. I get this error:
Note: C:\Users\Kyle\Desktop\TUSEG\Program\ProductDemo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
Anyway, when it tries to pull up a picture, I get this every time:
Couldn't find file: C:\Users\Kyle\Desktop\TUSEG\Program\images\microsoft\Xbox 360 Controller (PC).jpg
Couldn't find file: C:\Users\Kyle\Desktop\TUSEG\Program\images\microsoft\Wireless Laser Mouse 5000.jpg
The path is most definitely correct. I'm not sure what my problem is. If anyone could take a look at this and help me?
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class ProductDemo extends JPanel
implements ActionListener {
JLabel picture;
public ProductDemo() {
super(new BorderLayout());
String pMS[] = new String[23];
pMS[0] = ("LifeChat LX-3000");
pMS[1] = ("LifeChat ZX-6000");
pMS[2] = ("Wireless Notebook Presenter 8000");
pMS[3] = ("Arc Mouse");
pMS[4] = ("Bluetooth Notebook Mouse 5000");
pMS[5] = ("Explorer Mouse");
pMS[6] = ("Explorer Mini Mouse");
pMS[7] = ("Sidewinder X8 Mouse");
pMS[8] = ("Wireless Laser Mouse 5000");
pMS[9] = ("Wireless Mobile Mouse 3000");
pMS[10] = ("Wireless Mobile Mouse 6000");
pMS[11] = ("Arc Keyboard");
pMS[12] = ("Bluetooth Mobile Keyboard 6000");
pMS[13] = ("Sidewinder X4 Keyboard");
pMS[14] = ("Sidewinder X6 Keyboard");
pMS[15] = ("Ergonomic Desktop 7000");
pMS[16] = ("Wireless Desktop 3000");
pMS[17] = ("Wireless Laser Desktop 6000 v2.0");
pMS[18] = ("Wireless Media Desktop 1000");
pMS[19] = ("Windows Server 2008 Enterprise");
pMS[20] = ("Notebook Cooling Base");
pMS[21] = ("Xbox 360 Controller (PC)");
pMS[22] = ("Xbox 360 Controller");
Arrays.sort(pMS);
//Indices start at 0, so 4 specifies the last index of the product.
JComboBox msList = new JComboBox(pMS);
msList.setSelectedIndex(22);
msList.addActionListener(this);
//Set up the picture.
picture = new JLabel();
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
updateLabel(pMS[msList.getSelectedIndex()]);
picture.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
//height + width
picture.setPreferredSize(new Dimension(100, 100));
//Lays out the demo.
add(msList, BorderLayout.PAGE_START);
add(picture, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
/** Listens to the combo box. */
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String pMS = (String)cb.getSelectedItem();
updateLabel(pMS);
}
protected void updateLabel(String name) {
ImageIcon icon = createImageIcon("C:\\Users\\Kyle\\Desktop\\TUSEG\\Program\\images\\microsoft\\" + name + ".jpg");
picture.setIcon(icon);
if (icon != null) {
picture.setText(null);
}
else {
picture.setText("Image not found");
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = ProductDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ProductDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ProductDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You seem to be confusing a File based path like..
C:\Users\Kyle\Desktop\TUSEG\Program\images\microsoft\Xbox 360 Controller (PC).jpg
..with a relative reference for use in getResource(String), such as:
"images/microsoft/Xbox 360 Controller (PC).jpg"
The getResource() method expects a string using forward slashes, that is relative to the run-time class-path of the application (so the images directory etc. would most usually be added to a Jar). To ensure it works from a class from any package, prefix the string with /.
"/images/microsoft/Xbox 360 Controller (PC).jpg"
The getResource() method will return an URL, so be sure to use URL compatible constructors.
Decide if you want to load the images from the file system, or from the classpath of the application.
If from the file system, use file IO to load the icon, or the constructor taking a file name as argument:
ImageIcon icon = new ImageIcon("c:\\....jpg");
If from the classpath, then the path is a / separated path starting from the root of the classpath, and the images should be stored in the same directory/jar as your classes (or in another directory/jar that is in the classpath):
ImageIcon icon = new ImageIcon(ProductDemo.class.getResource("/path/to/image.jpg"));
See http://docs.oracle.com/javase/6/docs/api/javax/swing/ImageIcon.html and http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource%28java.lang.String%29

Categories