看不到JPanel

时间:2017-12-26 21:33:56

标签: java swing jpanel

我想知道为什么我无法在topPanel

中看到controlPanel

这是我的代码:

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

}

1 个答案:

答案 0 :(得分:1)

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

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

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

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