自定义JComponent大小默认为零吗? [英] Custom JComponent size default to zero?
问题描述
我正在尝试将自定义的可滚动JComponent添加到JFrame.
I'm trying to add a custom scrollable JComponent to a JFrame.
JScrollPane sp = new JScrollPane(hg);
frame.getContentPane().add(sp, BorderLayout.CENTER);
hg是我的自定义组件.
hg is my custom component.
问题是未显示我的自定义组件.但是,如果我这样做:
The problem is that my custom component is not displayed. However, if I do this:
hg.setBounds(0, 0, 800, 600);
然后将显示它.但是我当然不想明确设置大小.我希望它适合框架的中心.
Then it will be displayed. But of course I don't want to set size explicitly. I want it to fit in the center of the frame.
在我的自定义JComponent类中,我重写了getPreferredSize():
In my custom JComponent class, I override getPreferredSize():
private Dimension computePreferredSize() {
return new Dimension((int) (this.getParent().getSize().width * scale),
(int) (this.getParent().getSize().height * scale));
}
public Dimension getPreferredSize() {
Dimension d = computePreferredSize();
System.out.println("Dimension: " + d); // prints reasonable output: Dimension: java.awt.Dimension[width=1201,height=805]
return d;
}
但这似乎没有任何效果.即使我直接返回固定尺寸:
But this doesn't seem to have any effect. Even if I return a fixed dimension directly:
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
这也不起作用.
我还在我的ComponentUI的paint()方法中添加了println,但是没有打印任何内容,因此我认为出于某种原因未调用paint().我认为原因是我的自定义组件的大小默认为零,并且我不确定如何让其调整自己的大小.
I also added println in my ComponentUI's paint() method, but nothing is printed, so I think for some reason paint() is not called. I think the reason why is that my custom component's size defaults to zero, and I'm not sure how to let it adjust its own size.
所以我的问题是:为什么默认情况下不显示我的JComponent,我应该怎么做才能使其自动适应JFrame的中心?
So my question is: why my JComponent is not displayed by default, and what I should do to make it automatically fit into the center of the JFrame?
谢谢!
推荐答案
在定义hg
的类中,重写getPreferredSize()
以返回组件的首选大小.可以在此处和找到示例这里. 此处.
In the class that defines hg
, override getPreferredSize()
to return your component's preferred size. Examples may be found here and here. The rationale and some important caveats are discussed here.
这篇关于自定义JComponent大小默认为零吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!