Java Animation Using Timer

How To Create A Basic Animation Using Timer In Java Eclipse

java animation



In this Java Tutorial we will see How To Make A JFrame BackGround Color Animation Using Timer In Java Eclipse .




Project Source Code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Java_Timer_BackGround_Animation extends JFrame {

private JPanel contentPane;
    
Timer tm;
int i = 0;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Java_Timer_BackGround_Animation frame = new Java_Timer_BackGround_Animation();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public Java_Timer_BackGround_Animation() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Show Message");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 25));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(64, 35, 290, 89);
contentPane.add(lblNewLabel);
tm = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getContentPane().setBackground(new Color(i,i,i));
i++;
}
});
tm.start();
}

}




Share this

Related Posts

Previous
Next Post »

1 comments:

comments
29 avril 2018 à 12:50 delete

/**
* Create the frame.
* Adding stop timer.
*/
public Timer_BackGround_Animation() {
setTitle("Animation");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);

contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JLabel lblNewLabel = new JLabel("Show Message");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 25));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(64, 35, 290, 89);
contentPane.add(lblNewLabel);
try {
tm = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getContentPane().setBackground(new Color((int)i, (int)i, (int)i));
i++;
if (i >= 255) {
tm.stop();
}
}
});
tm.start();
} catch (Exception e) {
System.out.println(e.toString());
}
}

Reply
avatar