简体   繁体   中英

Java JFrame paint at keyevent

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.

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. ie, 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM