Reputation: 11
I had written a Java program in Swing to display an image in frame. But it is not working.
Do I have to add image in package in Netbeans?
Here is my code:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
//import java.awt.Image.*;
public class Images extends JFrame implements ActionListener {
JButton b;
JLabel l;
Images()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
ImageIcon i=new ImageIcon("stone.jpg");
b=new JButton("Click Me",i);
b.setBackground(Color.yellow);
b.setForeground(Color.red);
b.setFont(new Font("Arial",Font.BOLD,30));
Border bd=BorderFactory.createBevelBorder(BevelBorder.RAISED);
b.setBorder(bd);
b.setToolTipText("Buttons");
b.setMnemonic('C');
c.add(b);
b.addActionListener(this);
l=new JLabel();
c.add(l);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
ImageIcon i=new ImageIcon("stone.jpg");
l.setIcon(i);
}
public static void main(String args[])
{
Images d=new Images();
d.setTitle("Hello");
d.setSize(700,700);
d.setVisible(true);
}
}
Upvotes: 1
Views: 1654
Reputation: 18792
This ImageIcon i=new ImageIcon("stone.jpg");
should work if stone.jpg is stored at the project root directory.
If it it elsewhere, you need to modify the path.
For example if it is under resources use ImageIcon i=new ImageIcon("resources/stone.jpg")
.
To make sure the image was found you can use System.out.println(i.getIconWidth());
which will printout -1 if it wasn't.
Best practice is to use getResource
as described here.
Upvotes: 1