问题描述
我想在透明面板(在本例中为upperPanel
)上设置对象的动画,但是将动画对象添加到upperPanel
后,其背景将不再透明。
upperPanel
在bottomPanel
中。 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;
}
}
}