gpt4 book ai didi

java - 看不到 JPanel

转载 作者:行者123 更新时间:2023-12-02 11:49:28 28 4
gpt4 key购买 nike

我想知道为什么我在 controlPanel 中看不到 topPanel

这是我的代码:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class GUI {

private JFrame frame;
private JTextArea textArea;
private JPanel topPanel;
private JPanel controlPanel;
private JLabel topLabel;

void createScreen() {

frame = new JFrame("Hello");
frame.setSize(600,600);
frame.setLayout(new GridLayout(3,1));
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.setBackground(Color.GREEN);
topLabel = new JLabel("WELCOME TO MY TRAINING", JLabel.CENTER);

frame.add(topLabel);
frame.add(controlPanel);

topPanel = new JPanel();

BorderLayout borderLayout = new BorderLayout();

borderLayout.setHgap(10);
borderLayout.setVgap(10);

topPanel.setLayout(borderLayout);
topPanel.setBackground(Color.BLUE);
topPanel.setSize(75,300);
textArea = new JTextArea();
textArea.setSize(25, 25);

topPanel.add(textArea, BorderLayout.CENTER);

controlPanel.add(topPanel);

frame.setVisible(true);

}

public static void main(String[] args) {
GUI gui = new GUI();
gui.createScreen();
}

}

最佳答案

FlowLayout 使用组件的首选大小,而不是为其设置的实际大小。要解决您的问题,请将首选大小设置为 topPanel 而不是其 size

topPanel.setPreferredSize( new Dimension(75,300) );

但我的建议是避免像这样设置大小,而是让 TextArea 通过指定其行数和列数来确定大小,如下所示:

topPanel.setLayout(borderLayout);
topPanel.setBackground(Color.BLUE);
textArea = new JTextArea(10, 15);

关于java - 看不到 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47983919/

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