0

I have 8 jpanels with background color and I am trying to draw a rectangle on top of it but it shows under it and I cant get it on top

Here is the code for initializing a JPanel

tempPanel = new JPanel();
        tempPanel.setBackground(Color.black);
        tempPanel.setOpaque(true);
        tempPanel.setLayout(null);
        panel.add(tempPanel);
        tempPanel.setBounds(195 + insets.left, 155 + insets.top,
                main.getLanes().get(5).getDistance()*5, 20);
        if (!added)
            lanes.add(tempPanel);

and the code for drawing rectangle; it is inside a class that extends Jpanel and inisde paintComponents:

super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        drawLanes();
        int i, j;
        ArrayList<Lane> lanes2= new ArrayList<Lane>();
        ArrayList<Car> cars= new ArrayList<Car>();
        for(int counter = 0; counter < 10; counter ++) {
            lanes2 = main.getLanes();
            for( i = 0; i< lanes.size(); i++) {
                lanes.get(i).removeAll();
                cars = lanes2.get(i).getCars();
                for ( j = 0; j < cars.size(); j++) {
                    Insets insets = lanes.get(i).getInsets();
                    g2d.setColor(Color.red);
                    g2d.draw(new Rectangle(lanes.get(i).getLocation().x + 5*(lanes2.get(i).getDistance() - cars.get(j).getCurrent_pos()), lanes.get(i).getLocation().y,
                            cars.get(j).getCar_size()*5, lanes.get(i).getHeight()));
                    JLabel temp = new JLabel("Car");
                    temp.setForeground(Color.red);
                    temp.setBounds(insets.left + 5*(lanes2.get(i).getDistance() - cars.get(j).getCurrent_pos()) , insets.top,
                            cars.get(j).getCar_size()*5, lanes.get(i).getHeight());
                    lanes.get(i).add(temp);
                }
            }
        }

Thanks in adavnce

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Timo
  • 81
  • 1
  • 5
  • Possible duplicate of [How to draw in jPanel? (swing/graphics Java)](http://stackoverflow.com/questions/6118737/how-to-draw-in-jpanel-swing-graphics-java) and [How do I put graphics on a JPanel?](http://stackoverflow.com/questions/10488112/how-do-i-put-graphics-on-a-jpanel). – user1803551 Apr 24 '14 at 15:55
  • Look into `JLayeredPane` and the glass pane. – Andrew Thompson Apr 25 '14 at 04:03

0 Answers0