问题
I have strange problem with JComponent. I am trying to create my own JComponent and so I need to compose my JComponents together.
I wanted to paint JButton in my JComponent JDial:
public class JDial extends JComponent {
private static final long serialVersionUID = 3364481508702147328L;
public JDial() {
JButton b = new JButton("test");
this.add(b);
}
}
But that just paint nothing. Even more interesting is that this one works well:
public class JDial extends JPanel {
private static final long serialVersionUID = 3364481508702147328L;
public JDial() {
JButton b = new JButton("test");
this.add(b);
}
}
JPanel inherits from JComponent and paints JButton inside. How JPanel do this magic?
Thanks in advance
回答1:
Generally you would extend JComponent when you want to do custom painting by overriding the paintComponent() method.
If you just want to add a bunch of components then you should use a JPanel.
The difference between the two is that by default JPanel uses a FlowLayout so it know how to layout any component added to it. To make JComponent like a JPanel you would need to set the layout manager and add custom painting to paint the background.
回答2:
While JComponent also descends from Container
and does have all code to repaint properly sized and positioned children, it does not have any capability to resize or layout them. And you do not set neither size nor location for your JButton
so zero size is assumed by default.
Differently, JPanel
is created with FlowLayout
by default, this layout manager that will set component sizes mostly depending on they computed preferred sizes. In general, it is unusual to use JComponent
as container directly, use JPanel
.
来源:https://stackoverflow.com/questions/15591872/how-to-paint-jcomponent-in-jcomponent