how to set JPEG image to frame as background and then add
buttons on it.

Edited 4 Years Ago by rushikesh jadha: n/a

you can't put Image as background to JFrame, but

1) ContentPane

2) paintComponent for JPanel / JComponent

3) JLabel & Icon (notice JLabel haven't implemented any LayoutManager, you have to defin for that)

There are (as mKorbel said) a number of ways to do this, but in my personal opinion the easiest way is to subclass JPanel and override paintComponent to draw the image directly into the panel. Once you've done that all the rest of using the window (layout manager, adding conponents) etc is just the same as for a standard JFrame - it's a "set it and forget it" solution.
All you need is to subclass Jpanel, set an instance as your contentPane, load your image into an Image object,and in your subclass include

void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, this); 
}

If you want to re-size the image to fit the frame or anything like that it's just a couple of extra lines of code (hint: image.getScaledInstance(...) ).

Edited 4 Years Ago by JamesCherrill: n/a

Comments
for resize !0 but getWidht / getHeight

thanks for reply, i solved it myself.
below is function(method) which i use

public void addImage(JFrame f,String name,int x,int y) {
      try{  String path = name;
        File file = new File(path);
        BufferedImage image = ImageIO.read(file);
        JLabel label = new JLabel(new ImageIcon(image));
       // JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(label);
        f.pack();
        f.setLocation(x,y);
        f.setVisible(true);
      }catch(Exception e){e.printStackTrace();}
    }

Edited 4 Years Ago by rushikesh jadha: n/a

This article has been dead for over six months. Start a new discussion instead.