为什么这段代码的JTextArea占用了整个JFrame?

我希望我的框架的一部分包含JTextArea但它完全占用。 我无法在这里追踪错误。

import java.awt.*; import javax.swing.*; public class EchoServer { public static void main(String args[]) { CalcFrame c = new CalcFrame(); CalcTextArea a = new CalcTextArea(); } } class CalcTextArea { JTextArea historyDisplayer = new JTextArea("",50,20); CalcTextArea() { //historyDisplayer.setVisible(true); historyDisplayer.insert("Hello World", 0); Color bg = new Color(23,34,56); historyDisplayer.setBackground(bg); historyDisplayer.setBackground(bg); } } class CalcFrame extends CalcTextArea { JFrame frame = new JFrame(); CalcFrame() { frame.setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); frame.setTitle("CALCULATOR"); frame.setVisible(true); frame.add(historyDisplayer); } private static int DEFAULT_WIDTH = 299,DEFAULT_HEIGHT = 190; } 

默认情况下, JFrame使用BorderLayout 。 当你只是将一些东西添加到像JFrame这样的BorderLayout组件上时,它会添加到BorderLayout中心(如果你没有指定添加组件的位置),它会占用整个JFrame

您应该使用正确的布局来调整它们。

您可以尝试使用绝对布局。 它位于Layouts托盘上。

或者启用它:

 frame = new JFrame(); ... //your code here // to set absolute layout. frame.getContentPane().setLayout(null); 

这样,您可以随意将控件放在任何您喜欢的位置。