Java 使用背景色在jpanel顶部绘制二维图形形状

Java 使用背景色在jpanel顶部绘制二维图形形状,java,swing,user-interface,graphics,java-2d,Java,Swing,User Interface,Graphics,Java 2d,我有8个背景色的JPanel,我试图在它上面画一个矩形,但它显示在它下面,我不能在上面 下面是初始化JPanel的代码 tempPanel = new JPanel(); tempPanel.setBackground(Color.black); tempPanel.setOpaque(true); tempPanel.setLayout(null); panel.add(tempPanel); tempPanel.

我有8个背景色的JPanel,我试图在它上面画一个矩形,但它显示在它下面,我不能在上面

下面是初始化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);
以及绘制矩形的代码;它位于扩展Jpanel和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);
                }
            }
        }
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
拖带();
int i,j;
ArrayList lanes2=新的ArrayList();
ArrayList cars=新的ArrayList();
用于(整数计数器=0;计数器<10;计数器++){
lanes2=main.getLanes();
对于(i=0;i

非常感谢和的可能重复。查看
JLayeredPane
和玻璃窗格。