Why this code's JTextArea occupies entire JFrame?

两盒软妹~` 提交于 2019-12-20 03:16:38

问题


I expect part of my frame contains the JTextArea but it occupies entirely. I cannot trace the error here.

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

回答1:


JFrame by default uses BorderLayout. When you just add something onto a BorderLayout component like JFrame, it would add to the very center of the BorderLayout (if you did not specify where to add the component), and it takes up the entire JFrame.

You should use the correct layout to adjust them.




回答2:


You can try using Absolute layout. It's on the Layouts Pallet.

Or enable it with :

frame = new JFrame();
... //your code here

// to set absolute layout.
frame.getContentPane().setLayout(null);

This way, you can freely place the control anywhere you like.



来源:https://stackoverflow.com/questions/7748473/why-this-codes-jtextarea-occupies-entire-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!