I am trying to add a JPanel (well, several) to a JLayeredPane. However, when I do so, the paint component method of the JPanel seems to have no effect. An example is included below:
我正在尝试在JLayeredPane中添加一个JPanel(好,几个)。但是,当我这样做时,JPanel的paint组件方法似乎没有效果。下面是一个例子:
import javax.swing.*;
import java.awt.*;
public class Example {
public static void main(String[] args) {
// This Works as expected
JFrame usingPanel = new JFrame();
JPanel p = new JPanel();
p.add(new BluePanel());
usingPanel.setContentPane(p);
usingPanel.pack();
usingPanel.setVisible(true);
// This makes the frame but does not paint the BluePanel
JFrame usingLayer = new JFrame();
JLayeredPane l = new JLayeredPane();
l.setPreferredSize(new Dimension(200,200));
l.add(new BluePanel(), JLayeredPane.DEFAULT_LAYER);
JPanel p2 = new JPanel();
p2.add(l);
usingLayer.setContentPane(p2);
usingLayer.pack();
usingLayer.setVisible(true);
}
static class BluePanel extends JPanel{
public BluePanel(){
setPreferredSize(new Dimension(200,200));
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, 200, 200);
}
}
}
Why is this? and what are the possible solutions?
这是为什么呢?可能的解是什么?
2 个解决方案
#1
8
JLayeredPane does not have a LayoutManager, so you need to set the location and size of your panels yourself. See the tutorial
JLayeredPane没有LayoutManager,所以您需要自己设置面板的位置和大小。看教程
#2
1
-
you hardcoded the size on the screen and have to change from
您在屏幕上硬编码了大小,并且必须更改。
g.fillRect(0, 0, 200, 200);
to
来
g.fillRect(0, 0, getWidth(), getHeight());
-
(a minor change) add the method
(小改动)添加方法。
@Override public Dimension getPreferredSize() { return new Dimension(200, 200); }
and then remove of code line
setPreferredSize(new Dimension(200,200));
然后删除代码行setPreferredSize(新维度(200,200));
#1
8
JLayeredPane does not have a LayoutManager, so you need to set the location and size of your panels yourself. See the tutorial
JLayeredPane没有LayoutManager,所以您需要自己设置面板的位置和大小。看教程
#2
1
-
you hardcoded the size on the screen and have to change from
您在屏幕上硬编码了大小,并且必须更改。
g.fillRect(0, 0, 200, 200);
to
来
g.fillRect(0, 0, getWidth(), getHeight());
-
(a minor change) add the method
(小改动)添加方法。
@Override public Dimension getPreferredSize() { return new Dimension(200, 200); }
and then remove of code line
setPreferredSize(new Dimension(200,200));
然后删除代码行setPreferredSize(新维度(200,200));