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

Recommended Answers

All 7 Replies

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)

ok.
then how to set JPEG image to frame through label.

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(...) ).

commented: for resize !0 but getWidht / getHeight +11

how to set an instance as contentPane.

Use JFrame's setContentPane method ?

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();}
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.