File : Mover.java
package mover;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
class Mover{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() { // Run the GUI codes on the EDT
@Override
public void run() {
JFrame frame = new JFrame("Some Basic Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawingSpace());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
=============================================
File : DrawingSpace.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mover;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
class DrawingSpace extends JPanel{
private JLabel label;
private JButton button;
private Timer timer;
public DrawingSpace(){
setPreferredSize(new Dimension(200, 300));
initComponents();
add(label);
add(button);
}
public void initComponents(){
label = new JLabel("I am a JLabel !");
label.setBackground(Color.YELLOW);
label.setOpaque(true);
button = new JButton("Move");
//Move every (approx) 5 milliseconds
timer = new Timer(5, (ActionEvent e) -> {
//Move 1 px everytime
label.setLocation(label.getLocation().x, label.getLocation().y+1);
});
button.addActionListener((ActionEvent e) -> {
if(!timer.isRunning())
timer.start();
else
timer.stop();
});
}
}
Tidak ada komentar:
Posting Komentar