2

I was wondering if it was possible to place a created combo box on top of a Background picture placed on a JPanel. I am trying to do this however, i think the background image is overlapping my combo boxes so it doesn't appear. Any one know a clean way of having a background image on a JPanel with combo box on top and it positioned using box layout.

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
Marcello
  • 423
  • 1
  • 5
  • 12

2 Answers2

1

I think you should use the setComponentZOrder() method.

Here is an example: http://weblogs.java.net/blog/2009/01/21/swing-internals-paint-order

(Check the JavaDoc for more detailed information: setComponentZOrder() method

Joseph Farrugia
  • 327
  • 1
  • 3
  • 14
1

An alternative approach, and maybe more used, would see you override JPanel paintComponent and draw image directly to the Graphics object:

JFrame frame=...;

final BufferedImage bg=ImageIO.read(new URL("http://cs.anu.edu.au/student/comp6700/icons/DukeWithHelmet.png"));

JPanel p=new JPanel() {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d=(Graphics2D)g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

        g2d.drawImage(bg,0,0,null);
    }

    @Override
    public Dimension getPreferredSize() {//so our JPanel will fit the image entirely
        return new Dimension(bg.getWidth(),bg.getHeight());
    } 
};

frame.add(p);
frame.pack();
frame.setVisible(true);
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • 1
    In general, the ImageObserver argument passed to a drawImage method should be `this`, not null. Yes, it probably doesn't matter when you use a BufferedImage, but it's good practice. – VGR Jan 10 '13 at 00:30
  • 2
    Not _essential_ with `ImageIO.read()`; more [here](http://stackoverflow.com/q/1684422/230513). – trashgod Jan 10 '13 at 03:42
  • +1 to trashgod, @VGR, IMO it cannot be good practice if its unnecessary, than its just unnecessary... Good practice IMO is doing something that can be done in order to make code work more effectively and adding `this` does not. Its would actually be wrong in the context of my post. – David Kroukamp Jan 10 '13 at 16:29