本文介绍了如何在JComponent中绘制JComponent?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JComponent有一个奇怪的问题.我正在尝试创建自己的JComponent,因此需要将我的JComponent一起组成.

I have strange problem with JComponent. I am trying to create my own JComponent and so I need to compose my JComponents together.

我想在我的JComponent JDial中绘制JButton:

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继承自JComponent并在其内部绘制JButton. JPanel如何做到这一点?

JPanel inherits from JComponent and paints JButton inside. How JPanel do this magic?

预先感谢

推荐答案

通常,当您想通过覆盖paintComponent()方法进行自定义绘制时,将扩展JComponent.

Generally you would extend JComponent when you want to do custom painting by overriding the paintComponent() method.

如果只想添加一堆组件,则应该使用JPanel.

If you just want to add a bunch of components then you should use a JPanel.

两者之间的区别在于,默认情况下,JPanel使用FlowLayout,因此它知道如何对添加到其中的任何组件进行布局.要使JComponent像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.

这篇关于如何在JComponent中绘制JComponent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-12 03:57