JAVA 时间动画

JAVA Time Animation

我正在尝试使用添加和删除按钮的 Timer 制作一个简单的动画,但我不知道我哪里错了。我还添加了两个打印件只是为了验证。他们打印得恰到好处。我还观察到,如果我删除 removeAll() 方法,它会添加按钮。

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;


public class Animation extends JPanel{
    JLabel l1 = new JLabel(new ImageIcon("tom1.png"));
    JLabel l2 = new JLabel(new ImageIcon("tom2.png"));
    JLabel l3 = new JLabel(new ImageIcon("tom3.png"));
    JLabel l4 = new JLabel(new ImageIcon("tom4.png"));
    JLabel l5 = new JLabel(new ImageIcon("tom5.png"));
    JButton b1 = new JButton("HAHA");
    JButton b2 = new JButton();
    JPanel panel = new JPanel();

    public Animation(){
        setLayout(new BorderLayout());
        Timer time = new Timer(1000,new ActionListener(){
            public void actionPerformed(ActionEvent e){
                System.out.println("paint");
                add(b1, BorderLayout.CENTER);
                repaint();
                revalidate();
                System.out.println("remove");
                removeAll();
                repaint();
                revalidate();

            }
        });
        time.start();



    }


    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new Animation());
        frame.setVisible(true);
        frame.setSize(1000,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }



}

如评论中所说,您正在添加按钮然后删除 确实...

要使按钮一秒出现另一秒消失,您可以制作一个标志,并在计时器中一次做一件事,然后再做另一件事。 你可以这样做:

package test;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Animation extends JPanel {
    JLabel l1 = new JLabel(new ImageIcon("tom1.png"));
    JLabel l2 = new JLabel(new ImageIcon("tom2.png"));
    JLabel l3 = new JLabel(new ImageIcon("tom3.png"));
    JLabel l4 = new JLabel(new ImageIcon("tom4.png"));
    JLabel l5 = new JLabel(new ImageIcon("tom5.png"));
    JButton b1 = new JButton("HAHA");
    JButton b2 = new JButton();
    JPanel panel = new JPanel();
    boolean isthere = false;

    public Animation() {
        setLayout(new BorderLayout());
        Timer time = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if (!isthere) {
                    System.out.println("paint");
                    add(b1, BorderLayout.CENTER);
                    repaint();
                    revalidate();

                    isthere = !isthere;
                } else {

                    System.out.println("remove");
                    removeAll();
                    repaint();
                    revalidate();
                    isthere = !isthere;
                }

            }
        });
        time.start();

    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new Animation());
        frame.setVisible(true);
        frame.setSize(1000, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}