Adding an actionlistener to a JButton - java

public class BelishaBeacon {
public class Design extends JPanel {
private boolean alternateColors = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//creating the shapes
Rectangle box1 = new Rectangle(163, 180, 16, 45);
Rectangle box2 = new Rectangle(163, 225, 16, 45);
Rectangle box3 = new Rectangle(163, 270, 16, 45);
Rectangle box4 = new Rectangle(163, 315, 16, 45);
Rectangle box5 = new Rectangle(163, 360, 16, 45);
Rectangle box6 = new Rectangle(163, 405, 16, 45);
//drawing the shapes
Ellipse2D.Double ball = new Ellipse2D.Double(a, b, 100, 100);
g2.draw(ball);
g2.draw(box1);
g2.draw(box2);
g2.draw(box3);
g2.draw(box4);
g2.draw(box5);
g2.draw(box6);
//coloring the shapes
g2.setColor(Color.BLACK);
g2.fill(box1);
g2.fill(box3);
g2.fill(box5);
g2.setColor(Color.YELLOW);
g2.fill(ball);
if (alternateColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
alternateColors = false;
}
public void alternateColors() {
alternateColors = true;
repaint();
}
}
public BelishaBeacon() {
//frame
JFrame frame = new JFrame();
frame.setSize(330, 550);
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Design shapes = new Design();
JButton jbtFlash = new JButton("Flash");
jbtFlash.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Runnable r = new Runnable(){
#Override
public void run(){
while(/* user stops / toggleButton state*/ true)
{
swapColors(); // some method using static boolean
try{
Thread.sleep(500);
}catch(Exception e){}
}
}
private void swapColors() {
boolean swapColors;
Graphics g2;
if (swapColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
} else {
g2.setColor(Color.YELLOW);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
}
};
Thread t = new Thread(r);
t.start();
}});
JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.alternateColors();
}
});
I have created an action listener for my jbutton steady and flash, I am just trying to created a method for swapColors for it to be initialised in the jbutton flash. The swapcolos method initially should alternate between the colours orange and grey

You wrote that you want it to flash every 0.5 seconds.
To do so you need to start new thread for example
jbtFlash.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Runnable r = new Runnable(){
#Override
public void run(){
while(/* user stops / toggleButton state*/ true)
{
swapColors(); // some method using static boolean
try{
Thread.sleep(500);
}catch(Exception e){}
}
}
};
Thread t = new Thread(r);
t.start();
}});

if (alternateColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
alternateColors = false;
Should be:
if (alternateColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
} else {
g2.setColor(Color.YELLOW);
g2.fill(new Ellipse2D.Double(a, b, 100, 100));
}
AND
public void alternateColors() {
alternateColors = true;
repaint();
}
Should be:
public void alternateColors() {
//Flip boolean alternateColors
alternateColors = !alternateColors;
repaint();
}

Related

Drag a painted Shape

The Shape interface allows you to create shapes using different classes.
In the code below I create shapes using 3 different classes:
GeneralPath barBell = new GeneralPath();
barBell.append(new Ellipse2D.Double(100, 100, 75, 100), true);
barBell.append(new Rectangle2D.Double(150, 125, 175, 50), true);
barBell.append(new Ellipse2D.Double(300, 100, 75, 100), true);
shapePanel.addShape(barBell, Color.RED);
shapePanel.addShape(new Rectangle2D.Double(100, 300, 75, 150), Color.BLUE);
Polygon triangle = new Polygon();
triangle.addPoint(0, 0);
triangle.addPoint(100, 0);
triangle.addPoint(50, 100);
triangle.translate(400, 250);
shapePanel.addShape(triangle, Color.GREEN);
Resulting in a screen image:
Unfortunately the Shape interface does not provide any functionality for transforming the Shape.
For example to move the Shape to a new location I use the following:
if (dragShape instanceof Path2D)
((Path2D)dragShape).transform(AffineTransform.getTranslateInstance(deltaX, deltaY));
else if (dragShape instanceof Polygon)
((Polygon)dragShape).translate(deltaX, deltaY);
else if (dragShape instanceof RectangularShape)
{
RectangularShape rs = (RectangularShape)dragShape;
Rectangle r = rs.getBounds();
r.x += deltaX;
r.y += deltaY;
rs.setFrame( r );
}
I don't like the instanceof logic.
Is there a more generic approach to dragging any Shape around a panel that doesn't use instanceof logic?
Full example:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class ShapePanel2 extends JPanel
{
private ArrayList<ColoredShape> coloredShapes = new ArrayList<ColoredShape>();
public ShapePanel2()
{
DragListener dl = new DragListener();
addMouseListener(dl);
addMouseMotionListener(dl);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (ColoredShape cs : coloredShapes)
{
g2.setColor( cs.getForeground() );
g2.fill( cs.getShape() );
}
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(600, 500);
}
public void addShape(Shape shape, Color color)
{
ColoredShape cs = new ColoredShape(color, shape);
coloredShapes.add( cs );
repaint();
}
class ColoredShape
{
private Color foreground;
private Shape shape;
public ColoredShape(Color foreground, Shape shape)
{
this.foreground = foreground;
this.shape = shape;
}
public Color getForeground()
{
return foreground;
}
public void setForeground(Color foreground)
{
this.foreground = foreground;
}
public Shape getShape()
{
return shape;
}
}
class DragListener extends MouseAdapter
{
private Shape dragShape;
private Point pressed;
#Override
public void mousePressed(MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e))
{
pressed = e.getPoint();
for (int i = coloredShapes.size() - 1; i >= 0; i--)
{
ColoredShape cs = coloredShapes.get(i);
if (cs.getShape().contains( pressed ))
{
coloredShapes.remove(i);
coloredShapes.add(cs);
repaint();
dragShape = cs.getShape();
break;
}
}
}
}
#Override
public void mouseDragged(MouseEvent e)
{
if (dragShape != null)
{
int deltaX = e.getX() - pressed.x;
int deltaY = e.getY() - pressed.y;
if (dragShape instanceof Path2D)
((Path2D)dragShape).transform(AffineTransform.getTranslateInstance(deltaX, deltaY));
else if (dragShape instanceof Polygon)
((Polygon)dragShape).translate(deltaX, deltaY);
else if (dragShape instanceof RectangularShape)
{
RectangularShape rs = (RectangularShape)dragShape;
Rectangle r = rs.getBounds();
r.x += deltaX;
r.y += deltaY;
rs.setFrame( r );
}
pressed = e.getPoint();
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e)
{
dragShape = null;
}
}
private static void createAndShowGUI()
{
ShapePanel2 shapePanel = new ShapePanel2();
GeneralPath barBell = new GeneralPath();
barBell.append(new Ellipse2D.Double(100, 100, 75, 100), true);
barBell.append(new Rectangle2D.Double(150, 125, 175, 50), true);
barBell.append(new Ellipse2D.Double(300, 100, 75, 100), true);
shapePanel.addShape(barBell, Color.RED);
shapePanel.addShape(new Rectangle2D.Double(100, 300, 75, 150), Color.BLUE);
Polygon triangle = new Polygon();
triangle.addPoint(0, 0);
triangle.addPoint(100, 0);
triangle.addPoint(50, 100);
triangle.translate(400, 250);
shapePanel.addShape(triangle, Color.GREEN);
JFrame frame = new JFrame("ShapePanel2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(shapePanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}
One approach might be to convert each Shape to a GeneralPath as the Shape is added to the panel.
Now the dragging logic only needs to support a single class that implements the Shape interface:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class ShapePanel extends JPanel
{
private ArrayList<ColoredShape> coloredShapes = new ArrayList<ColoredShape>();
public ShapePanel()
{
DragListener dl = new DragListener();
addMouseListener(dl);
addMouseMotionListener(dl);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (ColoredShape cs : coloredShapes)
{
g2.setColor( cs.getForeground() );
g2.fill( cs.getShape() );
}
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(600, 500);
}
public void addShape(Shape shape, Color color)
{
// Convert the Shape to a GeneralPath so the Shape can be translated
// to a new location when dragged
ColoredShape cs = new ColoredShape(color, new GeneralPath(shape));
coloredShapes.add( cs );
repaint();
}
class ColoredShape
{
private Color foreground;
private GeneralPath shape;
public ColoredShape(Color foreground, GeneralPath shape)
{
this.foreground = foreground;
this.shape = shape;
}
public Color getForeground()
{
return foreground;
}
public void setForeground(Color foreground)
{
this.foreground = foreground;
}
public GeneralPath getShape()
{
return shape;
}
}
class DragListener extends MouseAdapter
{
private GeneralPath dragShape;
private Point pressed;
#Override
public void mousePressed(MouseEvent e)
{
// the clicked Shape will be moved to the end of the List
// so it is painted on top of all other shapes.
if (SwingUtilities.isLeftMouseButton(e))
{
pressed = e.getPoint();
for (int i = coloredShapes.size() - 1; i >= 0; i--)
{
ColoredShape cs = coloredShapes.get(i);
if (cs.getShape().contains( pressed ))
{
coloredShapes.remove(i);
coloredShapes.add(cs);
repaint();
dragShape = cs.getShape();
break;
}
}
}
}
#Override
public void mouseDragged(MouseEvent e)
{
if (dragShape != null)
{
int deltaX = e.getX() - pressed.x;
int deltaY = e.getY() - pressed.y;
dragShape.transform(AffineTransform.getTranslateInstance(deltaX, deltaY));
pressed = e.getPoint();
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e)
{
dragShape = null;
}
}
private static void createAndShowGUI()
{
ShapePanel shapePanel = new ShapePanel();
GeneralPath barBell = new GeneralPath();
barBell.append(new Ellipse2D.Double(100, 100, 75, 100), true);
barBell.append(new Rectangle2D.Double(150, 125, 175, 50), true);
barBell.append(new Ellipse2D.Double(300, 100, 75, 100), true);
shapePanel.addShape(barBell, Color.RED);
shapePanel.addShape(new Rectangle2D.Double(100, 300, 75, 150), Color.BLUE);
Polygon triangle = new Polygon();
triangle.addPoint(0, 0);
triangle.addPoint(100, 0);
triangle.addPoint(50, 100);
triangle.translate(400, 250);
shapePanel.addShape(triangle, Color.GREEN);
JFrame frame = new JFrame("ShapePanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(shapePanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}

adding and removing panels when rectangles intersect

I'm making a game and when the user is in one of the game map panels he should enter the game once the character rectangle intersects with the game button rectangle on the map. The user navigates the character using the arrow keys.
I have the following code in the keyPressed method for one of the map panels (its the same for the rest) and the button (game1) reacts to the intersection as it should but the add and remove statements aren't adding or removing the respective panels:
Rectangle rb1 = character.getBounds();
Rectangle rb2 = game1.getBounds();
if (rb1.intersects(rb2)){
game1.setText("Int");
game1.setBackground(Color.red);
remove(sp);
add(g1, "Center");
validate();
repaint();
}
Initially I thought putting that block in the keyPressed method was what's causing the issue but when i moved it, the game1 button stopped reacting entirely. Any help is welcomed and appreciated :)
Here is the code in that panel:
public class SportsPanel extends javax.swing.JPanel implements KeyListener {
JButton homeButton2;
JButton game1;
JButton game2;
JButton game3;
JButton game4;
JButton game5;
SportsPanel sp;
JLabel character;
CharacterMenu cm;
ControlPanel cp;
game1 g1;
game2 g2;
game3 g3;
game4 g4;
game5 g5;
JTextField scoreField;
int c =1;
int x = 100;
int y = 100;
public SportsPanel() {
cm = new CharacterMenu();
g1 = new game1();
g2 = new game2();
g3 = new game3();
g4 = new game4();
g5 = new game5();
setLayout(null);
setBackground(Color.white);
homeButton2 = new JButton("Back to Main Menu");
add(homeButton2);
homeButton2.setBounds(10, 629, 150, 40);
character = new JLabel("");
character.setBounds(x, y, 100, 100);
add(character);
game1 = new JButton("Game 1");
add(game1);
game1.setBounds(200,200, 100, 20);
game2 = new JButton("Game 2");
add(game2);
game2.setBounds(340, 20, 100, 20);
game3 = new JButton("Game 3");
add(game3);
game3.setBounds(120,458, 100, 20);
game4 = new JButton("Game 4");
add(game4);
game4.setBounds(458,269, 100, 20);
game5 = new JButton("Game 5");
add(game5);
game5.setBounds(2, 500, 100, 20);
setFocusable(true);
addKeyListener(this);
scoreField = new JTextField(" Time elapsed: ");
scoreField.setBounds(10, 10, 150, 50);
add(scoreField);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
requestFocusInWindow();
Image myImage = Toolkit.getDefaultToolkit().getImage("images/sports.png");
g.drawImage(myImage, 0, 0, 925, 699, this);
if(c == 1){
ImageIcon lion1 = new ImageIcon("images/lion.png");
ImageIcon newSize = new ImageIcon(((lion1).getImage()).getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH));
character.setText("");
character.setIcon(newSize);
}
if(c == 2){
ImageIcon franklin1 = new ImageIcon("images/franklin.png");
ImageIcon newSize = new ImageIcon(((franklin1).getImage()).getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH));
character.setText("");
character.setIcon(newSize);
}
if(c == 3){
ImageIcon saquon1 = new ImageIcon("images/saquon.png");
ImageIcon newSize = new ImageIcon(((saquon1).getImage()).getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH));
character.setText("");
character.setIcon(newSize);
}
}
#Override
public void keyTyped(KeyEvent evt) {
}
#Override
public void keyPressed(KeyEvent evt) {
System.out.println("Key pressed");
int kk = evt.getKeyCode();
if (kk == evt.VK_LEFT)
{
x = x - 5;;
}
if (kk == evt.VK_RIGHT)
{
x = x + 5;
}
if (kk == evt.VK_UP)
{
y = y - 5;
}
if (kk == evt.VK_DOWN)
{
y = y + 5;
}
character.setBounds(new Rectangle(x, y, 100, 100));
Rectangle rb1 = character.getBounds();
Rectangle rb2 = game1.getBounds();
if (rb1.intersects(rb2)){
game1.setText("Int");
game1.setBackground(Color.red);
remove(sp);
add(g1, "Center");
validate();
repaint();
}
}
#Override
public void keyReleased(KeyEvent evt) {
}
}

Repainting/refreshing the JFrame

I have a "car" made with various objects using graphics g and I want to move it when a button is pressed. With that, I had no problem, but I have a problem with its path. When the car is moved, the old position is not cleared out.
Code of the car (to move when button is pressed):
static void gPostavi2(Graphics g){
Graphics2D g2d = (Graphics2D) g;
for(int x=500; x>89; x--){
//risanje
g2d.setColor(Color.blue);
g2d.fillRect(x+10, 351, 118, 23);
g2d.fillRect(x+12, 321, 30, 40);
g2d.fillRect(x+45, 330, 83, 20);
g2d.setColor(Color.black);
g2d.fillOval(x+19, 362, 20, 20);
g2d.fillOval(x+90, 362, 20, 20);
g2d.drawString("2t", x+70, 344);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In this class are only methods for moving things around, the class extends another that has non-moving objects, buttons, labels,... and the paintComponent method.
How can I clear the old position, every time the for statement goes around ?
EDIT: some more code down here. In the main class I have only this code:
public static void main(String[] args) {
staticnaGrafika.dodajGumbe();
}
In staticnaGrafika I have a ton of code, but this is the beginning of paintComponent:
public class staticnaGrafika extends JPanel{
staticnaGrafika(){
setBorder(BorderFactory.createLineBorder(Color.black));
}
public Dimension getPreferredSize(){
return new Dimension(1100, 740);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
//opticno stikalo
//preveri, ce ga plosca prekriva pri max. dvigu
g2d.setColor(Color.black);
g2d.fillOval(21, 148, 33, 33);
g2d.setColor(Color.yellow);
g2d.fillOval(22, 149, 31, 31);
g2d.setColor(Color.black);
g2d.fillRect(13, 159, 11, 1); //el. prikljucnice
g2d.fillRect(13, 166, 10, 1);
g2d.drawOval(7, 157, 5, 5);
g2d.drawOval(7, 164, 5, 5);
//naslon; spodnji omejevalec hoda bata
g2d.setColor(Color.black);
g2d.fillRect(5, 350, 13, 43);
g2d.fillRect(5, 380, 63, 13);
g2d.fillRect(262, 350, 408, 13);
g2d.fillRect(262, 350, 13, 43);
g2d.fillRect(212, 380, 63, 13);
there is just painting in here. Below I have another method, which adds buttons, actionListeners:
public static void dodajGumbe() {
final JFrame f = new JFrame();
//dvig, stop, spust
JButton dvig = new JButton("DVIGNI");
dvig.setBackground(Color.WHITE);
dvig.setFocusPainted(false);
dvig.setBounds(850,15,120,30);
JButton stop = new JButton("STOP");
stop.setBackground(Color.WHITE);
stop.setFocusPainted(false);
stop.setBounds(850,50,120,30);
JButton spust = new JButton("SPUSTI");
spust.setBackground(Color.WHITE);
spust.setFocusPainted(false);
spust.setBounds(850,85,120,30);
//komande bremen
JButton postavi2 = new JButton("nalozi breme");
postavi2.setBackground(Color.WHITE);
postavi2.setFocusPainted(false);
postavi2.setBounds(760,240,120,30);
JButton odvzemi2 = new JButton("razlozi breme");
odvzemi2.setBackground(Color.WHITE);
odvzemi2.setFocusPainted(false);
odvzemi2.setBounds(760,275,120,30);
JButton postavi5 = new JButton("nalozi breme");
postavi5.setBackground(Color.WHITE);
postavi5.setFocusPainted(false);
postavi5.setBounds(760,330,120,30);
JButton odvzemi5 = new JButton("razlozi breme");
odvzemi5.setBackground(Color.WHITE);
odvzemi5.setFocusPainted(false);
odvzemi5.setBounds(760,365,120,30);
Container gumbi = f.getContentPane();
spust.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
dinamicnaGrafika.gSpusti(f.getGraphics());
}});
dvig.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
dinamicnaGrafika.gDvigni(f.getGraphics());
}});
stop.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
dinamicnaGrafika.gStop(f.getGraphics());
}});
postavi2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
dinamicnaGrafika.gPostavi2(f.getGraphics());
}});
odvzemi2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
dinamicnaGrafika.gOdvzemi2(f.getGraphics());
}});
postavi5.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
dinamicnaGrafika.gPostavi5(f.getGraphics());
}});
odvzemi5.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
dinamicnaGrafika.gOdvzemi5(f.getGraphics());
}});
gumbi.add(dvig);
gumbi.add(stop);
gumbi.add(spust);
gumbi.add(postavi2);
gumbi.add(odvzemi2);
gumbi.add(postavi5);
gumbi.add(odvzemi5);
f.getContentPane();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new staticnaGrafika());
f.pack();
f.setVisible(true);
}
You probably forgot to call
super.paintComponent(g);
in your paintComponent() method
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g); //Clear screen before redraw
//Your codes for painting..
}
You should never be calling sleep() on the UI thread. Instead, I highly recommend that you use javax.swing.Timer and an ActionListener. Something like:
void paintCar(Graphics2D g2d, int x) {
g2d.setColor(Color.blue);
g2d.fillRect(x+10, 351, 118, 23);
g2d.fillRect(x+12, 321, 30, 40);
g2d.fillRect(x+45, 330, 83, 20);
g2d.setColor(Color.black);
g2d.fillOval(x+19, 362, 20, 20);
g2d.fillOval(x+90, 362, 20, 20);
g2d.drawString("2t", x+70, 344);
}
int x = 0;
public MyConstructor() {
new Timer(5, this).start();
}
public void actionPerformed(ActionEvent ae) {
x++;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
paintCar(g2d, x);
}
It looks like the problem lies with your implementation. You could create a class for your Car objects and each car object keep track of their own coordinates.
For your case, if you are only moving the cars only when the button is clicked, you don't even need a Timer. Just update the car's position in the ActionListener for every button click.
OUTPUT:
class Car
{
private Color carColor;
private int x, y;
private int speed;
private static int carWidth = 100;
private static int carHeight = 30;
public Car(Color carColor, int speed){
this.carColor = carColor;
this.speed = speed;
x = 0;
y = 0;
}
public void moveTo(int x, int y){
this.x = x;
this.y = y;
}
public void draw(Graphics g){
//Draw a car object
g.setColor(carColor);
g.fillRect(x, y, carWidth, carHeight);
g.setColor(Color.BLACK);
//Draw Wheels
g.fillOval(x, y+carHeight, 30, 30);
g.fillOval(x+carWidth-30, y+carHeight, 30, 30);
}
public int getX(){return x;}
public int getY(){return y;}
public int getSpeed(){return speed;}
}
So when you move your car(s), just update their positions and that's all you need to do. Pay special attention to my paintComponent() method. You should keep that method simple and clutter free. It is only responsible for painting. All the movements of cars is done else where.
class DrawingSpace extends JPanel implements ActionListener{
Car c1, c2, c3;
public DrawingSpace(){
setPreferredSize(new Dimension(800, 400));
c1 = new Car(Color.RED, 5);
c2 = new Car(Color.GREEN, 8);
c3 = new Car(Color.BLUE, 10);
c1.moveTo(10, 50);
c2.moveTo(10, 180);
c3.moveTo(10, 280);
}
public void moveCars(){
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
c1.draw(g);
c2.draw(g);
c3.draw(g);
}
#Override
public void actionPerformed(ActionEvent e){
//Used for timer (to animate moving cars)
c1.moveTo((c1.getX()+c1.getSpeed()), c1.getY());
c2.moveTo(c2.getX()+c2.getSpeed(), c2.getY());
c3.moveTo(c3.getX()+c3.getSpeed(), c3.getY());
if(c1.getX() > 800)
c1.moveTo(0, c1.getY());
if(c2.getX() > 800)
c2.moveTo(0, c2.getY());
if(c3.getX() > 800)
c3.moveTo(0, c3.getY());
repaint();
}
}
For a task like this, it will be better and easier to use javax.swing.timer instead of implementing your own loop with Thread.sleep().
class MovingCars{
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame f = new JFrame("Moving Cars");
DrawingSpace ds = new DrawingSpace();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(ds);
f.pack();
f.setLocationRelativeTo(null);
Timer t = new Timer(50, ds); //Delay of 50 milliseconds
t.start();
}
});
}
}

Animation in Java on top of JPanel

I have a JPanel where I have array of buttons. It's a kind of memory game, and I wont to show some few frames of animation, for example Double Point.
Here is a part of code:
This animation is that some text is slowly showing and disappearing (I used also Alpha channel in those images) , but I don't know why when id should slowly disapearing it didn't like if of this image stay there.
public void paintComponent(Graphics g)
{
//Image img = new ImageIcon("res\\double.png").getImage();
//g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
t.start();
Image img2 = new ImageIcon("res\\double\\double_0000"+i+".png").getImage();
g.drawImage(img2, 0, 0, this.getWidth(), this.getHeight(), null);
}
#Override
public void actionPerformed(ActionEvent e) {
i++;
if(i>30)
t.restart();
repaint();
}
}
public class ScoreWindow extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
final public JButton btnScoreReturnButton;
final public JLabel ScoreLabel;
//final public JScrollBar scrollScoreBar;
private String[] data;
Timer t;
String sth="";
int i=0;
int datapower=0;
public ScoreWindow() {
btnScoreReturnButton = new JButton("Powrót");
SpringLayout sl_ScoreWindow = new SpringLayout();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, btnScoreReturnButton, 27, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, btnScoreReturnButton, 11, SpringLayout.WEST, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, btnScoreReturnButton, 100, SpringLayout.WEST, this);
this.setLayout(sl_ScoreWindow);
this.add(btnScoreReturnButton);
ScoreLabel = new JLabel();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, ScoreLabel, 64, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, ScoreLabel, 111, SpringLayout.WEST, this);
sl_ScoreWindow.putConstraint(SpringLayout.SOUTH, ScoreLabel, -15, SpringLayout.SOUTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, ScoreLabel, -76, SpringLayout.EAST, this);
this.add(ScoreLabel);
JLabel SubtitleLabel = new JLabel();
sl_ScoreWindow.putConstraint(SpringLayout.NORTH, SubtitleLabel, 20, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.WEST, SubtitleLabel, 80, SpringLayout.WEST,ScoreLabel);
sl_ScoreWindow.putConstraint(SpringLayout.SOUTH, SubtitleLabel, 60, SpringLayout.NORTH, this);
sl_ScoreWindow.putConstraint(SpringLayout.EAST, SubtitleLabel, -150, SpringLayout.EAST, this);
SubtitleLabel.setForeground(Color.BLACK);
SubtitleLabel.setHorizontalAlignment(JLabel.CENTER);
SubtitleLabel.setVerticalAlignment(JLabel.CENTER);
SubtitleLabel.setFont(ScoreLabel.getFont().deriveFont(32.0f));
SubtitleLabel.setText("Najlepsze Wyniki");
this.add(SubtitleLabel);
t=new Timer(100,this);
}
public void ReadData()
{
data = new String[20];
FileReader readFile=null;
BufferedReader reader =null;
String temp;
try
{
readFile=new FileReader("highscore.dat");
reader=new BufferedReader(readFile);
int i=0;
while((temp=reader.readLine())!=null)
{
data[i]=temp;
i++;
}
}
catch(Exception e)
{
data[0] ="Nobody:0";
}
finally
{
try {
if(reader!=null)
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void LoadData() {
String stream="<html>";
//System.out.print(data[0]+"\n");
for(int i=0;i<data.length;i++)
{
if(data[i]!=null)
{
if(i==0)
stream=stream+data[i];
//tream=stream+data[i];
else if(i>0)
stream=stream+"<br>"+data[i];
}
}
stream+="</html>";
System.out.print(stream+"\n");
ScoreLabel.setHorizontalAlignment(JLabel.CENTER);
ScoreLabel.setVerticalAlignment(JLabel.CENTER);
ScoreLabel.setForeground(Color.WHITE);
ScoreLabel.setFont(ScoreLabel.getFont().deriveFont(16.0f));
ScoreLabel.setText(stream);
ScoreLabel.setOpaque(false);
}
public int AmoutofData()
{
String amount[] = ScoreLabel.getText().split("<br>");
return amount.length;
}
public void paintComponent(Graphics g)
{
t.start();
if(i<10)
sth="0"+i;
else
sth=i+"";
Image img2 = new ImageIcon("res\\double\\double_000"+sth+".png").getImage();
g.drawImage(img2, i, i, 100, 100, null);
}
#Override
public void actionPerformed(ActionEvent e) {
i++;
if(i>30)
i=0;
repaint();
}
}

Create basic animation

How can I create basic animation in Java?
Currently i am trying to implement a basic animation program using swing in Java.
But i am not getting whether my logic for program in correct or not.
My program implements Runnable, ActionListener interfaces and also extends JApplet.
I want to know that, is it necessary to differentiate start method of JApplet and Runnable?
And if yes then why..?
My program is basic balloon program, when I click on start button balloons start moving upward and comes to floor again. This will be continue till i press stop button.
Here is my code.
public class Balls extends JApplet implements Runnable{
private static final long serialVersionUID = 1L;
JPanel btnPanel=new JPanel();
static boolean flag1=true;
static boolean flag2=true;
static boolean flag3=false;
static int h;
static int temp=10;
Thread t=new Thread(this);
JButton start;
JButton stop;
public void init()
{
try
{
SwingUtilities.invokeAndWait(
new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Can't create GUI because of exception");
System.exit(0);
}
}
private void makeGUI() {
start=new JButton("start");
stop=new JButton("stop");
btnPanel.add(start);
btnPanel.add(stop);
add(btnPanel,BorderLayout.NORTH);
}
public void run()
{
while(true)
{
if(flag1)
{
repaint();
flag1=false;
}
else
{
try
{
wait();
flag3=true;
}
catch(InterruptedException e)
{
JOptionPane.showMessageDialog(null,"Error ocuured !!\n Exiting..");
System.exit(0);
}
}
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int h=Integer.parseInt(getParameter("height"));
if (flag1)
{
g.setColor(Color.RED);
g.fillOval(10,h,50,50);
g.setColor(Color.YELLOW);
g.fillOval(50,h,20,20);
g.setColor(Color.CYAN);
g.fillOval(70,h,80,30);
g.setColor(Color.BLUE);
g.fillOval(120,h,50,60);
g.setColor(Color.GRAY);
g.fillOval(160,h,70,50);
g.setColor(Color.GREEN);
g.fillOval(200,h,80,80);
g.setColor(Color.MAGENTA);
g.fillOval(260,h,80,30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320,h,60,40);
g.setColor(Color.pink);
g.fillOval(370,h,65,45);
flag1=false;
}
else
{
g.setColor(Color.RED);
g.fillOval(10,h-temp,50,50);
g.setColor(Color.YELLOW);
g.fillOval(50,h-temp,20,20);
g.setColor(Color.CYAN);
g.fillOval(70,h-temp,80,30);
g.setColor(Color.BLUE);
g.fillOval(120,355,50,60);
g.setColor(Color.GRAY);
g.fillOval(160,h-temp,70,50);
g.setColor(Color.GREEN);
g.fillOval(200,h-temp,80,80);
g.setColor(Color.MAGENTA);
g.fillOval(260,h-temp,80,30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320,h-temp,60,40);
g.setColor(Color.pink);
g.fillOval(370,h-temp,65,45);
if(flag2 && temp<=400)
{
temp+=10;
if(temp==400)
{
flag2=false;
}
}
else if(!flag2)
{
temp-=10;
if(temp==10)
{
flag2=true;
}
}
else
{
}
}
}
public void start()
{
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t.start();
if(flag3)
{
notify();
}
}
});
stop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
flag1=false;
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
repaint();
t=null;
}
}
});
}
}
1) Use SwingTimer as recommended instead of your Runnable implementation.
2) Read about custom painting , and here
3) draw at the JPanel instead of on JFrame
I have changed your code, examine it. I think, that it does what you want.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Balls extends JApplet {
private static final long serialVersionUID = 1L;
JPanel btnPanel = new JPanel();
static boolean flag1 = true;
static boolean flag2 = true;
static boolean flag3 = false;
static int h;
static int temp = 10;
JButton start;
JButton stop;
private Timer timer;
public void init() {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
makeGUI();
}
});
}
private void makeGUI() {
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
repaint();
}
});
start = new JButton("start");
stop = new JButton("stop");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
timer.start();
}
});
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
timer.stop();
}
});
btnPanel.add(start);
btnPanel.add(stop);
add(new MyPanel(), BorderLayout.CENTER);
add(btnPanel, BorderLayout.NORTH);
}
class MyPanel extends JPanel{
public void paintComponent(Graphics g) {
super.paintComponent(g);
int h = Integer.parseInt(getParameter("height"));
if (flag1) {
g.setColor(Color.RED);
g.fillOval(10, h, 50, 50);
g.setColor(Color.YELLOW);
g.fillOval(50, h, 20, 20);
g.setColor(Color.CYAN);
g.fillOval(70, h, 80, 30);
g.setColor(Color.BLUE);
g.fillOval(120, h, 50, 60);
g.setColor(Color.GRAY);
g.fillOval(160, h, 70, 50);
g.setColor(Color.GREEN);
g.fillOval(200, h, 80, 80);
g.setColor(Color.MAGENTA);
g.fillOval(260, h, 80, 30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320, h, 60, 40);
g.setColor(Color.pink);
g.fillOval(370, h, 65, 45);
flag1 = false;
} else {
g.setColor(Color.RED);
g.fillOval(10, h - temp, 50, 50);
g.setColor(Color.YELLOW);
g.fillOval(50, h - temp, 20, 20);
g.setColor(Color.CYAN);
g.fillOval(70, h - temp, 80, 30);
g.setColor(Color.BLUE);
g.fillOval(120, 355, 50, 60);
g.setColor(Color.GRAY);
g.fillOval(160, h - temp, 70, 50);
g.setColor(Color.GREEN);
g.fillOval(200, h - temp, 80, 80);
g.setColor(Color.MAGENTA);
g.fillOval(260, h - temp, 80, 30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320, h - temp, 60, 40);
g.setColor(Color.pink);
g.fillOval(370, h - temp, 65, 45);
if (flag2 && temp <= 400) {
temp += 10;
if (temp == 400) {
flag2 = false;
}
} else if (!flag2) {
temp -= 10;
if (temp == 10) {
flag2 = true;
}
} else {
}
}
}
}
}

Categories

Resources