I am creating a simple program in which I want to display an Image and a button.So I've created a JFrame
.
This JFrame
contains tow JPanel
and one of the panels contains JButton
and the other panel contains my image. But image is not displaying in the panel. When I add image to the JFrame
, it is displaying normally. Please help with the following code!
main()
method:
public class NewClass2 {
public static void main(String args[]){
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrame frm = new JFrm();
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setSize(500,500);
}
});
}
}
JFrm
class which initialize JFrame
:
class JFrm extends JFrame{
JButton button;
JPanel panel0,panel1;
JFrm(){
panel0 = new JPanel();
panel1 = new JPanel();
button = new JButton("Start");
button.setPreferredSize(new Dimension(100, 30));
panel0.add(button);
panel1.add(new ImageComponent()); //adding image component to panel1 is not working
//add(new ImageComponent()); //adding image component to the frame is working ..
add(panel1,BorderLayout.PAGE_START);
add(panel0,BorderLayout.PAGE_END);
}
}
ImageComponent
class which adds the image:
class ImageComponent extends JComponent{
Image img;
ImageComponent(){
img = new ImageIcon("C:\\Users\\Kaushal28\\Desktop\\Aqua-Ball-icon.png").getImage();
}
@Override
public void paint(Graphics g){
g.drawImage(img, 100,100 , null);
}
}
How can I add image to JPanel
?