【发布时间】:2015-03-15 20:18:44
【问题描述】:
我正在创建一个模拟类型的应用程序,我想要一个背景层和另一个层用于所有动画。我目前正在使用 JlayeredPanes,但我无法让顶层的背景显示为透明,因此我可以看到背景,非常感谢任何帮助,代码如下:
背景层
public class SimBackground extends JLayeredPane{
private Model theModel;
private SimulationArea simulationArea;
public SimBackground(Model theModel){
this.theModel=theModel;
setBackground(new Color(0, 230, 0));
setOpaque(true);
setPreferredSize(new Dimension(500,500));
setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
for(int x=0;x<50;x++){
for(int y=0;y<50;y++){
g.drawRect((x*10), (y*10), 10, 10);
}
}
}
顶层
public class SimulationArea extends JLayeredPane {
private int SPEED = 100;
private Model theModel;
Timer timer;
public SimulationArea(Model theModel){
this.theModel = theModel;
setPreferredSize(new Dimension(500,500));
setLocation(0,0);
setOpaque(false);
setBackground(new Color(0,0,0,0));
setVisible(true);
//Swing Timer
timer = new Timer(SPEED,new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
update();
repaint();
revalidate();
}
});
}
private void update() {
theModel.update();
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
//test get 1 active object
ArrayList<ActiveObject> activeObjects = theModel.getActiveObjects();
//System.out.println(activeObjects.size());
for(int i=0; i<activeObjects.size(); i++){
ActiveObject activeObject = theModel.getActiveObjects().get(i);
int x = activeObject.getCoordinates().getX();
int y = activeObject.getCoordinates().getY();
int size = activeObject.getSize();
g2d.fillRect (x ,y , size, size);
}
}
有人可以告诉我我在这里缺少什么吗?
【问题讨论】:
-
等等,顶层扩展了JLayeredPane?对不起,但这让我困惑不已。您的 JLayeredPane 不应该是所有的底部,即包含 所有 层的容器吗?并且任何层都不应扩展 JLayeredPane。 JPanel 或 JComponent,是的,但不是 JLayeredPane。您应该在 JPanel 的
paintComponent(...)方法中绘制,而不是在 JLayeredPane 中绘制。并阅读 JLayeredPane 教程,因为您似乎还不知道如何使用它们。你可以在这里找到它......how to use layered panes -
那些只是窗格,我还没有发布面板的代码,如果它们不扩展 JlayeredPane 我怎么能在他们自己的类中创建它们?我在他们自己的班级中找不到他们的任何例子
-
您将使用单个 JLayeredPane,可能不会对其进行扩展,并且您会将扩展 JPanel 或 JComponent 的对象添加到单个 JLayeredPane。这个网站上有很多使用它的例子,有些是我写的。
标签: java swing transparent jlayeredpane