Custom JComponent size default to zero?

2019-07-24 16:48发布

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条回答
Explosion°爆炸
2楼-- · 2019-07-24 17:14

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.

查看更多
登录 后发表回答