gpt4 book ai didi

java - 使用流布局初始化多个 JPanel(家庭作业)

转载 作者:行者123 更新时间:2023-11-29 10:04:29 27 4
gpt4 key购买 nike

我正在尝试使用 FlowLayout 创建一个内部插入了两个 JPanel 的 JFrame。我在一个单独的文件中初始化了框架,但这是我被调用的内容

public class FlowInFlow extends JFrame
{
public FlowInFlow() {

setLayout(new FlowLayout());

JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel1.setBackground(Color.RED);

JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel2.setBackground(Color.BLUE);

}
}

编辑:当我运行它时,当我需要并排放置两个框时,我只会得到一个空白框

最佳答案

正如我已经说过的,JPanel 的默认首选大小是 0x0...

这意味着当您将它添加到像 FlowLayout 这样的布局时,使用首选大小,它会出现...嗯...不会

enter image description here

public class TestFlowLayout {

public static void main(String[] args) {
new TestFlowLayout();
}

public TestFlowLayout() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JPanel master = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel left = new JPanel();
left.setBackground(Color.RED);
left.add(new JLabel("Lefty"));

JPanel right = new JPanel();
right.setBackground(Color.BLUE);
right.add(new JLabel("Righty"));

master.add(left);
master.add(right);

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(master);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

关于java - 使用流布局初始化多个 JPanel(家庭作业),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13170559/

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