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 ==
Related
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/.
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
Its been a while since i built a desktop JAVA application.. after lots of documentation and doing implementation tests, i still have not found an image grid solution.
Either Java lacks such a ready-to-use component (?!) or you tell me to brush up my google-fu. :)
I have a very simple technical premises: a JDialog that allows the user to pick an image. Input is a Map<Integer, String> list that holds filenames. Output is the Integer key the user chose. GUI also is simple: user chooses 1 image using mouse or keyboard, and dialog closes. All images are 80x80px and loaded from filename, not a resource.
I tried several approaches so far this morning:
Search for components/widgets that show scrollable imagegrid that can flow to the left. (no dice)
Search for components/widgets that show scrollable imagegrid (no dice)
Search for any components/widgets/gui-libs (no dice .. do these even exist?!)
Try and implement myJList.setModel(), but i cant get it to just take my Map<> and show thumbnails. (overcomplicates!)
Try and implement myJPanel.setlayout(new FlowLayout(..)) with several myJPanel.add(new JButton(..)) which just creates a bunch of JButton on a JPanel, which each need a event handler. I wonder how scrolling and keyboard input is going to work out, and how i'm supposed to keep/reference my Map<> key values. (overcomplicates?)
In lieu of your answer, i am now working on the latter, which should work but i cant believe everyone needs to reinvent the same GUI wheel here. How to have the user select an image from my Map<Integer, String>? Are there JAVA libraries/widgets/components that i should look to avoid this?
I hope this isn't being modded down, i have no working implementation with error to show you guys.. this question is about how/where to find the components or what approaches would be better. Its 2014 and i cant believe that JAVA still requires me to build my own "GUI component" just to see some images.. not even Delphi or Mono does that.
If all you want is a grid of images, and having them selectable, consider using a JList, filling it with appropriate ImageIcons, and giving it a ListSelectionListener. In the Listener you can close the enclosing dialog when a selection has been made.
You state:
Try and implement myJList.setModel(), but i cant get it to just take my Map<> and show thumbnails. (overcomplicates!)
You need to use your Map to populate your ListModel, and set that Model to the JList's model.
For example:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
#SuppressWarnings("serial")
public class ImageGridPanel extends JPanel {
public static final String PATH = "http://images-2.drive.com.au/2011/";
public static final String[] CARS = {
"04/15/2308961/giulietta_1024-80x80.jpg",
"11/18/2781958/audi-a1-sportback_600-80x80.jpg",
"12/23/2856762/fiat-500-80x80.jpg",
"01/12/2129944/Honda-Civic-Sedan-concept-1_600-80x80.jpg",
"12/23/2856581/mini-roadster-80x80.jpg",
"12/23/2856571/hyundai-veloster-80x80.jpg",
"12/23/2856771/hyundai-i30-80x80.jpg",
"12/23/2856580/mini-coupe-80x80.jpg" };
private DefaultListModel<Car> carModel = new DefaultListModel<>();
final JTextField textField = new JTextField(20);
public ImageGridPanel() {
for (String carPath : CARS) {
String path = PATH + carPath;
try {
URL imgUrl = new URL(path);
BufferedImage img = ImageIO.read(imgUrl);
ImageIcon icon = new ImageIcon(img);
String name = carPath.substring(carPath.lastIndexOf("/"));
name = name.substring(1, name.lastIndexOf("-"));
carModel.addElement(new Car(name, icon));
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
ShowGridAction showAction = new ShowGridAction("Car Grid", carModel);
JButton showGridBtn = new JButton(showAction);
add(showGridBtn);
add(textField);
}
private class ShowGridAction extends AbstractAction {
private CarGridPanel carGridPanel;
public ShowGridAction(String name, DefaultListModel<Car> carModel) {
super(name);
carGridPanel = new CarGridPanel(carModel);
}
public CarGridPanel getCarGridPanel() {
return carGridPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor((Component) e.getSource());
JDialog dialog = new JDialog(win, "Cars", ModalityType.APPLICATION_MODAL);
dialog.add(carGridPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
int x = dialog.getLocation().x;
int y = dialog.getLocation().y - 150;
dialog.setLocation(x, y);
dialog.setVisible(true);
Car selectedCar = carGridPanel.getSelectedCar();
if (selectedCar != null) {
textField.setText(selectedCar.getName());
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ImageGrid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ImageGridPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Car {
String name;
Icon icon;
public Car(String name, Icon icon) {
this.name = name;
this.icon = icon;
}
public String getName() {
return name;
}
public Icon getIcon() {
return icon;
}
}
#SuppressWarnings("serial")
class CarGridPanel extends JPanel {
private JList<Car> carList = new JList<>();
private Car selectedCar;
public CarGridPanel(ListModel<Car> model) {
carList.setModel(model);
carList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
carList.setVisibleRowCount(2);
carList.setCellRenderer(new DefaultListCellRenderer() {
#Override
public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value != null) {
Car carValue = (Car) value;
value = carValue.getIcon();
} else {
value = "";
}
return super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
}
});
setLayout(new BorderLayout());
add(new JScrollPane(carList));
carList.addListSelectionListener(new ListListener());
}
public Car getSelectedCar() {
return selectedCar;
}
private class ListListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
selectedCar = carList.getSelectedValue();
Window win = SwingUtilities.getWindowAncestor(CarGridPanel.this);
win.dispose();
}
}
}
No, Java doesn't have what you want.
Java is a general-purpose programming language, not a toolset, particularly not a specialized desktop GUI toolset. This is not a denigration of the language, just a statement of a purpose that it was not developed to fulfill.
If Delphi or Mono or anything has your particular widget, then I suggest you program in that, instead. This is not a denigration of you, just an observation that, if you do not want to put together the widget you want from lower-level components and code, then Java is not the right language/tool for you to use to do it.
As for not believing that Java "still requires" you to build your own component, I can only say that you don't get to choose which languages provide which features. I'm just as glad Java isn't littered with your component and the hundreds of others that people like you would come up with that they think Java should provide. It's big enough as it is.
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 );
}
}
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