简体   繁体   English

扩展JPanel的问题

[英]Problem with extending JPanel

I have an abstract entity: 我有一个抽象实体:

public abstract class Entity extends JPanel implements FocusListener

And I have a TextEntity: 我有一个TextEntity:

public class TextEntity extends Entity

Inside TextEntity's constructor I want to put a JTextArea that will cover the panel: 在TextEntity的构造函数内部,我想放置一个JTextArea来覆盖面板:

textArea = new JTextArea();
textArea.setSize(getWidth(),getHeight());
add(textArea);

But getWidth() and getHeight() returns 0. Is it a problem with the inheritance or the constructor? 但是getWidth()getHeight()返回0。是继承还是构造函数问题?

Shuldn't be an inheritance problem. 应该不是继承问题。 Probably in the constructor the JPanel doesn't still have a size. 可能在构造函数中,JPanel仍然没有大小。

Try using some LayoutManager that takes care of resizing the components inside the panel. 尝试使用一些LayoutManager来调整面板内部组件的大小。 For example the BorderLayout, and add the textarea to the center. 例如,BorderLayout,然后将文本区域添加到中心。

Something like this (it's been a few years since I coded Swing): 像这样的东西(我编写Swing已有几年了):

textArea = new JTextArea();
textArea.setSize(getWidth(),getHeight());
setLayout(new BorderLayout());
add(textArea, BorderLayout.CENTER);

Now, when you make the panel visible, the layout manager should take care of keeping the textarea the same size as the panel. 现在,当您使面板可见时,布局管理器应注意使textarea与面板大小相同。 Also make sure you don't have any borders in the panel. 还要确保面板上没有边框。

根据布局,您需要设置嵌入式组件的首选/最小/最大大小,以便包装计算实际大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM