透明面板上的动画

问题描述

我想在透明面板(在本例中为upperPanel)上设置对象的动画,但是将动画对象添加upperPanel后,其背景将不再透明。

upperPanelbottomPanel中。 bottomPanel的背景为红色,因此您可以查看upperPanel是否透明。

框架代码

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class NewFrame extends JFrame{
    
      public static void main(String args[]){
          JFrame f = new JFrame();
          Animatedobject a = new Animatedobject();
          JPanel bottomPanel = new JPanel();
          JPanel upperPanel = new JPanel();
          bottomPanel.setBackground(Color.red);
          bottomPanel.setSize(300,300);
          bottomPanel.setLayout(new BorderLayout());
          upperPanel.setSize(300,300);
          upperPanel.setopaque(false);
          upperPanel.setLayout(new BorderLayout());
          f.add(bottomPanel);
          bottomPanel.add(upperPanel);
          upperPanel.add(a);
          f.setSize(400,400);
          f.setVisible(true);
          f.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
      }
}

动画对象的代码

import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public class Animatedobject extends javax.swing.JPanel implements ActionListener{

    private int x = 0;
    private int y = 0;
    private boolean direction = true;
    Timer tm = new Timer(50,this);

    public Animatedobject() {
        initComponents();
        tm.start();
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(new java.awt.Color(102,102,102));
        g.fillRect(x,y,30,30);
        System.out.println("Test gesetzt("+x+"|"+y+")");
    }
    
    public void moveForward() {
        x = x + 30;
        repaint();
        System.out.println("(" + x + "|" + y + ")");
    }

    public void moveBackwards() {
        x = x - 30;
        repaint();
        System.out.println("(" + x + "|" + y + ")");
    }

    public void moveDown() {
        y = y + 30;
        repaint();
        System.out.println("(" + x + "|" + y + ")");
    }

    public void moveUp() {
        y = y - 30;
        repaint();
        System.out.println("(" + x + "|" + y + ")");
    }

    public void actionPerformed(ActionEvent e) {
       if (direction){
           moveDown();
       }
       else {
           moveUp();
       }
       if (((y >= 270) && (direction)) || ((y <= 0) && (!direction))) {
        moveForward();
        direction = !direction;
       }
      }
}

解决方法

因为您的面板使用的是BorderLayout,这将迫使子组件填充父组件的整个可用空间,因为AnimatedObject本身并不透明,因此它会用其填充父组件的空间不透明的填充颜色。

您可以通过更改AnimatedObject的背景颜色进行测试

public AnimatedObject() {
    setBackground(Color.BLUE);
    tm.start();
}

Blue background

一个简单的解决方法就是也使AnimatedObject透明。

public AnimatedObject() {
    setOpaque(false);
    tm.start();
}

Transparent