gpt4 book ai didi

JAVA时间动画

转载 作者:行者123 更新时间:2023-12-01 11:57:17 25 4
gpt4 key购买 nike

我正在尝试使用计时器制作一个简单的动画,添加和删除按钮,但我不知道我错在哪里。我还添加了两张照片以供验证。他们打印得恰到好处。我还观察到,如果我删除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);

}

}

关于JAVA时间动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28351551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com