Reputation: 51
I use Java to build a simple interface, and it says no error. However it can't display the 1ImageIcon1 on the button (it only has the name of the button.). How can I fix it?
Here is the code.
public static void main(String[] args) {
JFrame frame=new JFrame("Hi everyone");
frame.setSize(500,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane=new JPanel();
Font font=new Font(Font.SERIF, Font.BOLD,20);
JLabel label=new JLabel("How about a presidation quote");
label.setFont(font);
pane.add(label);
ImageIcon icon=new ImageIcon("ChenGao.jpg");
JButton ChenGao = new JButton("ChenGao",icon);
ChenGao.setHorizontalTextPosition(SwingConstants.CENTER);
ChenGao.setVerticalTextPosition(SwingConstants.BOTTOM);
pane.add(ChenGao);
JTextArea textArea= new JTextArea(10,40);
textArea.setText("Yes we can");
pane.add(textArea);
frame.setContentPane(pane);
frame.setVisible(true);
}
Upvotes: 0
Views: 245
Reputation: 12140
You can read Oracle's online API about ImageIcon. use a relative path like:
new ImageIcon("src/ChenGao.jpg")
Upvotes: 0
Reputation: 347184
Generally, there are (at least) two types of "resources" that get discussed, external and internal.
An external resource is one that resides outside of the application context, such as a file on the file system. An internal resource is one the resides within the context of the application. These are also know as embedded resources, as they live within the classpath context of the application, normally within one or more Jar files.
In this case, you can not access them like normal files, instead, you need to use Class#getResource
or Class#getResourceAsInputStream
, depending on your needs.
Based on your comments, I would suggert that you need to use either
ImageIcon icon = new ImageIcon(getClass().getResource("ChenGao.jpg"));
or maybe
ImageIcon icon = new ImageIcon(getClass().getResource("/ChenGao.jpg"));
Depending on where the image is relative to the class trying to load it.
You may also need to supply a path if the image is contained within some directory within the source directory
Because ImageIcon
doesn't provide any useful information if loading failed for some reason, you're normally better off using ImageIO
to load your images. This will, at least, throw an exception if something goes wrong
Check out Reading/Loading an Image for more details.
Upvotes: 1