Question

I want to update my rectangle when my key is pressed currently I have almost achieved that

package com.raggaer.frame;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class Elements extends JPanel {

    private static int y = 250;

    public Elements() {

        this.getInputMap().put(KeyStroke.getKeyStroke("UP"), "up");
        this.getActionMap().put("up", new Listener("up"));
        this.getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "down");
        this.getActionMap().put("down", new Listener("down"));
    }

    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        g.drawRect(250, this.y, 10, 10);
    }

    public Dimension getPreferredSize() {

        return new Dimension(500, 500);
    }

    public static void setY(int cord) {

        y += cord;
            // Cant access repaint()
    }
}

And this is my listener class

package com.raggaer.frame;

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.AbstractAction;

public class Listener extends AbstractAction {

    private String code;

    //final Elements game = new Elements();

    public Listener(String order) {

        this.code = order;
    }

    public void actionPerformed(ActionEvent e) {

        System.out.println(this.code);

        Elements.setY(1);
    }
}

Currently everything works except that I dont know how to update the y position of the rectangle, I tried using an static variable but then I cant call the repaint() method.

Was it helpful?

Solution

No,.... don't use static anything, neither methods nor fields because if you do this, you'll break object-oriented programming rules, leaving your code difficult to update and maintain. The exception of course would be your main method, and carefully chosen fields and methods who truly belong to the class. Instead give the class that needs to call the Element object's method a valid reference to the object whose state you wish to change, the drawing JPanel or Element object. This can be done by passing in a valid reference via a constructor parameter.

public class Listener extends AbstractAction {
  private Elements elements;

  public Listener(Elements elements) {
    this.elements = elements;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top