编写程序以使用java swing滚动文本

-3 java animation swing

有两个java文件Animate和Anim1.Anim1文件有JFrame,我想附加Animate文件,它具有屏幕滚动的文本逻辑(应该是JFrame屏幕).但我找不到方法.并且还有代码抛出以下编译时错误 - 线程"Thread-0"中的异常java.lang.Error:未解决的编译问题:方法repaint()未定义为类型Animation

import java.awt.Graphics;

public class Animation implements Runnable {
    int x=500;
    String s="hello world";
    public void run(){
        while(true){
            repaint();
            try{
                Thread.sleep(50);
            }catch(InterruptedException e){
                e.printStackTrace();
                }

        }

    }
    public void paint(Graphics g){
        g.drawString("hello world", x,-10 );
        x--;
        if(x< -100){
            x=500;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)
import java.awt.Component;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Anim1 {
    public static void main(String[] args){
        Animation a= new Animation();
        Thread t= new Thread(a);
        t.start();

        JFrame frame= new JFrame("animate");
        frame.setVisible(true);
        frame.setSize(400,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    }
}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

重绘方法可以在Swing组件中找到 - 对于paint和paintComponent也是如此.除非你在另一个作为组件的对象上进行重绘调用,否则在不扩展Swing comopnent的类中调用它是没有意义的.同样地给一个非组件类一个paint方法是没有意义的,因为你没有覆盖任何绘制方法.

可能你的Animation类应该扩展JPanel,以便它可以覆盖paintComponent(而不是 paint),这样repaint()调用才有意义.同时始终使用注释预先绘制您的绘制方法(或您认为覆盖父方法的任何其他方法)@Override.这样,当您没有正确地(或根本不)覆盖方法时,编译器会向您抱怨.你还想在你的覆盖中调用super的绘画方法.

最重要的是:阅读Swing绘画教程,因为它们都在那里解释.退房:执行自定义绘画

你的绘画方法看起来像这样:

@Override
protected void paintComponent(Graphics g) {
    // always call the super's method to clean "dirty" pixels
    super.paintComponent(g);

    // then draw the String. Make y a field too, so it can be controlled
    // more easily
    g.drawString(s, x, y);
}
Run Code Online (Sandbox Code Playgroud)

请注意,我不会更改x值或在我的绘制方法中调用任何状态更改代码,这是设计的.该方法的paintComponent是画.您不必在是否或者即使它会被称为完全控制,并且它可以被称为倍.

相反,x值应该在"游戏循环"中更改,这里是Runnable的run()方法.另外,根据我的评论,虽然可以使用Thread/Runnable创建此代码,但使用Swing Timer来驱动动画更安全,因为这样可以避免担心Swing线程问题.