Question

Currently Im trying to update my rectangle position at keyevent but I dont know how to call the paintComponent method from another class or how to achieve this

Paint class

package com.raggaer.frame;

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

import javax.swing.JPanel;

public class Elements extends JPanel {

    public Elements() {


    }

    public void paintComponent(Graphics g) {

        super.paintComponent(g);

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

    public Dimension getPreferredSize() {

        return new Dimension(500, 500);
    }
}

And my listener class

package com.raggaer.frame;

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

public class Listener implements KeyListener {

    public void keyPressed(KeyEvent e) {

        System.out.println(e.getExtendedKeyCode());
    }

    public void keyReleased(KeyEvent e) {



    }

    public void keyTyped(KeyEvent e) {

    }

    public void paintComponent(Graphics g) {

        g.drawRect(10, 10, 20, 20);
    }
}

I tried adding a method inside the listener class called paintComponent but I need to pass a graphic object.. dont know how to achieve this.

I was thinking on drawing a rectangle using variables and at keyevent modify that variables but I dont know if thats the correct way to do it.

Was it helpful?

Solution

Recommendations:

  • You don't call paint or paintComponent directly.
  • Having the paintComponent in another class will do nothing of use for you.
  • If you want to move the rectangle that you draw, don't use hard-coded numbers. Use fields that can be changed. So rather than g.drawRect(250, 250, 10, 10);, have g.drawRect(rectX, rectY, rectW, rectH);. Edit, As you yourself suggest, "I was thinking on drawing a rectangle using variables and at keyevent modify that variables but I dont know if thats the correct way to do it."
  • Give the painting JPanel class these fields plus public setter methods that will allow other classes the ability to change the field states, and then call repaint. i.e, setRectX(int rectX), setRectY(int rectY), etc...
  • Calling repaint on the drawing JPanl will usually trigger the painting mechanisms to initiate a painting sequence, and this will call (indirectly) the JPanel's paintComponent method.
  • Don't use a KeyListener if you can avoid it, but rather use Key Bindings. For an example program on use of these, please have a look here.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top