java - My drawn object doesn't clear previous rectangle after key is pressed -
my code not clear previous rectangle when press 1 of arrow keys. thought using repaint()
in keypressed()
method, solve problem. tried using clearrect()
, doesn't anything.
this idle rectangle:
this when hold down right arrow key:
here code:
import java.awt.component; import java.awt.dimension; import java.awt.graphics; import java.awt.graphics2d; import java.awt.event.keyevent; import java.awt.geom.rectangle2d; import javax.swing.icon; import java.awt.*; import java.awt.event.keyevent; import java.awt.event.keylistener; import java.awt.geom.affinetransform; import java.awt.geom.arc2d; import java.awt.geom.pathiterator; import java.awt.geom.point2d; import java.awt.geom.rectangle2d; import java.util.arraylist; import javax.swing.icon; import javax.swing.jcomponent; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.joptionpane; import javax.swing.jpanel; public class rectangle extends jpanel implements keylistener{ private int height; private int width; private int x; private int y; private graphics2d g2; public rectangle(int width, int height,int x, int y) { this.height = height; this.width = width; this.x = x; this.y = y; jlabel label = new jlabel(); label.addkeylistener(this); label.setfocusable(true); label.setopaque(true); label.addkeylistener(this); this.add(label); label.requestfocusinwindow(); setvisible(true); } public dimension getpreferredsize() { return new dimension(500,500); } public void keypressed(keyevent e) { if (e.getkeycode() == keyevent.vk_down) { y = y + 5; repaint(); } if (e.getkeycode() == keyevent.vk_left) { x = x - 5; repaint(); } if (e.getkeycode() == keyevent.vk_up) { y = y - 5; repaint(); } if (e.getkeycode() == keyevent.vk_right) { x = x + 5; repaint(); } } public void keyreleased(keyevent e) {} public void keytyped(keyevent e) {} public void paintcomponent(graphics g) { this.g2 = (graphics2d) g; g2.drawrect(x, y, width, height); } }
test class
import java.awt.dimension; import java.awt.flowlayout; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.swingutilities; public class test { public static void main(string[] args) { swingutilities.invokelater(new runnable() { public void run() { createandshowgui(); } }); } private static void createandshowgui() { jframe f = new jframe("rectangle"); f.setdefaultcloseoperation(jframe.exit_on_close); f.add( new rectangle(40,20,250,250)); f.pack(); f.setvisible(true); } }
you have missed add super.paintcomponent(g);
breaking flow.
this working fine code making single line changes.
public void paintcomponent(graphics g) { super.paintcomponent(g); // add line this.g2 = (graphics2d) g; g2.drawrect(x, y, width, height); }
please read more painting in awt , swing
Comments
Post a Comment