简体   繁体   English

秋千上的自定义组件有问题

[英]Problem with custom component on swing

I'm not used to GUI development, but now I need it a little bit, and I want to avoid reading all documentation just because of this problem. 我不习惯于GUI开发,但是现在我需要一点,并且我想避免仅仅因为这个问题而阅读所有文档。

I'm having trouble displaying a custom component like the one I posted below. 我在显示自定义组件(如我在下面发布的组件)时遇到麻烦。 If I add it to a JFrame it works fine, but I cant add more then one, and if I add it to a JPanel it wont be displayed at all. 如果我将其添加到JFrame中,则可以正常工作,但不能再添加一个,如果将其添加至JPanel中,则根本不会显示。

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;

public class Test extends JComponent implements Runnable {

    private int c,x,y;

    public Test(int x,int y){
        c = 0;
        this.x = x;
        this.y = y;
    }

    private void inc(){
        c++;
        if(c>255){
            c = 0;
        }
    }

    public void paint(Graphics g) {
        g.setColor(new Color(c,c,c));
        g.fillRect(x, y, 50, 50);
    }

    public void run() {
        while(true){
            inc();
            try{
                Thread.currentThread().sleep(20);
            } catch (Exception e){
            }
            repaint();
        }
    }
}

and I want to avoid reading all documentation just because of this problem. 并且我想避免仅仅因为这个问题而阅读所有文档。

Yes, well reading actually saves time because you do things correctly the first time and you don't have to sit around waiting/hoping someone answers your question. 是的,良好的阅读实际上可以节省时间,因为您可以在第一时间正确地做事,而不必坐在那里等待/希望别人回答您​​的问题。

So start with the Swing tutorial 因此,从Swing教程开始

1) Custom painting is done by overriding the paintComponent() method. 1)通过覆盖paintComponent()方法来完成自定义绘制。 Read the section from the Swing tutorial on "Custom Painting". 阅读Swing教程中有关“自定义绘画”的部分。

2) Animation should be done by using the Swing Timer, see the section from the tutorial on "How to Use Timers". 2)动画应该通过使用Swing计时器来完成,请参见教程中“如何使用计时器”部分。

3) In fact you don't event need to create a custom component. 3)实际上,您不需要创建自定义组件。 All you need to do is create a JPanel, set its preferred size, and then use a Timer to change its background. 您需要做的就是创建一个JPanel,设置其首选大小,然后使用Timer更改其背景。

As a bare minimum, you should also setPreferredSize(x+50, y+50) and setMininumSize(x+50, y+50) in the constructor to let layout manager know about your component's size for placing it in the container widget properly. 至少,您还应该在构造函数中设置setPreferredSize(x + 50,y + 50)和setMininumSize(x + 50,y + 50),以使布局管理器了解组件的大小,以便将其正确放置在容器小部件中。

Also, calling repaint() not from AWTEventThread is quite bad. 另外,不是从AWTEventThread调用repaint()是非常糟糕的。 Use SwingUtilities.invokeLater() for that. 为此使用SwingUtilities.invokeLater()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM