gpt4 book ai didi

java - 将 JPanel 添加到 JLayeredPane 会导致绘制和调整大小不起作用

转载 作者:行者123 更新时间:2023-12-02 12:26:30 25 4
gpt4 key购买 nike

我正在尝试将 JPanel(好吧,几个)添加到 JLayeredPane。但是,当我这样做时,JPanel 的绘制组件方法似乎没有效果。下面包含一个示例:

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);
}


}


}

这是为什么呢?可能的解决方案是什么?

最佳答案

JLayeredPane 没有 LayoutManager,因此您需要自己设置面板的位置和大小。请参阅tutorial

关于java - 将 JPanel 添加到 JLayeredPane 会导致绘制和调整大小不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8415920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com