4
Contributors
7
Replies
8
Views
5 Years
Discussion Span
Last Post by rushikesh jadha
Featured Replies
  • 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) … Read More

1

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)

1

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 by JamesCherrill: n/a

Votes + Comments
for resize !0 but getWidht / getHeight
0

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 by rushikesh jadha: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.