dimanche 29 mars 2015

java animation, making an object change color every 'x' seconds



hi there i was just wondering if someone could help me or give me some advice with timers, the problem i have got is that i need an object to change color every x seconds on click of a button 'flash' and stay a single color on click of a button 'steady' so far i have got my buttons to work i just cant seem to get the object to 'flash'(change color on its own). my code is below and works without problems.



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


/**
* Created by joe on 26/03/15.
*/

class Beacon extends JPanel {
private boolean lightOn = true;

private int x = 150;
private int y = 90;
private int ballSize = 55;

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (lightOn){
g2.setColor(Color.BLACK);
g2.fillRect(172, 140, 12, 30);
g2.drawRect(172, 170, 11, 30);
g2.fillRect(172, 200, 12, 30);
g2.drawRect(172, 230, 11, 30);
g2.fillRect(172, 260, 12, 30);
g2.drawRect(172, 290, 11, 30);
g2.fillRect(172, 320, 12, 30);
g2.drawRect(172, 350, 11, 30);
g2.setColor(Color.ORANGE);
g2.fillOval(x, y, ballSize, ballSize);
}
else{
g2.setColor(Color.BLACK);
g2.fillRect(172, 140, 12, 30);
g2.drawRect(172, 170, 11, 30);
g2.fillRect(172, 200, 12, 30);
g2.drawRect(172, 230, 11, 30);
g2.fillRect(172, 260, 12, 30);
g2.drawRect(172, 290, 11, 30);
g2.fillRect(172, 320, 12, 30);
g2.drawRect(172, 350, 11, 30);
g2.setColor(Color.GRAY);
g2.fillOval(x, y, ballSize, ballSize);
} }
public void lightOn() { lightOn = true; }
public void lightOff() { lightOn = false; }
}

public class BeaconViewer extends JFrame
{
JButton Flash = new JButton("Flash");
JButton Steady = new JButton("Steady");
JPanel bPanel = new JPanel();
Beacon bbPanel = new Beacon();



public BeaconViewer()
{
bPanel.add(Flash);
this.add(bPanel, BorderLayout.SOUTH);
bPanel.add(Steady);
this.add(bbPanel, BorderLayout.CENTER);
Flash.addActionListener(new FlashListener());
Steady.addActionListener(new SteadyListener());
}

class FlashListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
bbPanel.lightOff();
repaint();

}

}

class SteadyListener implements ActionListener {

public void actionPerformed(ActionEvent a) {
bbPanel.lightOn();
repaint();
}

}

public static void main(String[] args) {
JFrame scFrame = new BeaconViewer();
scFrame.setTitle("Belish Beacon");
scFrame.setSize(300, 500);
scFrame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
scFrame.setVisible(true); }}



Aucun commentaire:

Enregistrer un commentaire