Custom JComponent size default to zero?

こ雲淡風輕ζ 提交于 2020-01-05 12:58:14

问题


I'm trying to add a custom scrollable JComponent to a JFrame.

JScrollPane sp = new JScrollPane(hg);
frame.getContentPane().add(sp, BorderLayout.CENTER);

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.

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

This doesn't work either.

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.

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?

Thank you!


回答1:


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.



来源:https://stackoverflow.com/questions/13666245/custom-jcomponent-size-default-to-zero

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