我对JComponent有个奇怪的问题。我正在尝试创建我自己的JComponent,因此我需要将我的JComponents组合在一起。
我想在我的JComponent JDial中绘制JButton:
public class JDial extends JComponent {
private static final long serialVersionUID = 3364481508702147328L;
public JDial() {
JButton b = new JButton("test");
this.add(b);
}
} 但那什么也没画出来。更有趣的是,这个方法运行得很好:
public class JDial extends JPanel {
private static final long serialVersionUID = 3364481508702147328L;
public JDial() {
JButton b = new JButton("test");
this.add(b);
}
}JPanel继承自JComponent,并在内部绘制JButton。JPanel是如何做到这一点的?
提前感谢
发布于 2013-03-24 05:17:11
通常,当您想要通过覆盖paintComponent()方法进行自定义绘制时,可以扩展JComponent。
如果你只想添加一堆组件,那么你应该使用JPanel。
两者之间的区别在于,默认情况下,JPanel使用FlowLayout,因此它知道如何对添加到其中的任何组件进行布局。要使JComponent像JPanel一样,您需要设置布局管理器并添加自定义绘画来绘制背景。
发布于 2013-03-24 05:15:57
虽然JComponent也是从Container派生出来的,并且确实有所有代码来重新绘制适当大小和位置的子级,但它没有任何调整大小或布局的功能。而且您没有为您的JButton设置大小和位置,因此默认情况下假定大小为零。
不同的是,默认情况下,JPanel是用FlowLayout创建的,这个布局管理器主要根据组件计算的首选大小来设置组件大小。一般来说,直接使用JComponent作为容器是不常见的,请使用JPanel。
https://stackoverflow.com/questions/15591872
复制相似问题