java - What is causing this code to repaint itself? -



java - What is causing this code to repaint itself? -

in code below, arrow keys used draw line in etch-a-sketch (but have resize window first trigger panel's focus request @ right time -- that's question different time, perhaps). graphics command g.drawline() occurs in keypressed() function, repaint() not called explicitly, image updates arrow keys pressed. why that? documentation have looked @ talks jpanel automatically repainting when resized or uncovered.

import java.awt.event.*; import java.awt.*; import javax.swing.*; public class etch extends jpanel implements keylistener{ public int xprev, yprev, xnew, ynew, inc; public etch(int start){ xprev = start; yprev = start; xnew = start; ynew = start; inc = 10; addkeylistener(this); } public void paintcomponent(graphics g){ super.paintcomponent(g); this.requestfocusinwindow(); } public static void main(string[] args) { jframe w = new jframe("keyboard"); w.setbounds(100, 100, 600, 600); w.setdefaultcloseoperation(jframe.exit_on_close); etch panel = new etch(200); panel.setfocusable(true); panel.setbackground(color.red); container c = w.getcontentpane(); c.add(panel); w.setresizable(true); w.setvisible(true); } public void keypressed(keyevent e){ int code = e.getkeycode(); if (code == keyevent.vk_up){ xprev = xnew; yprev = ynew; ynew -= inc; } if (code == keyevent.vk_down){ xprev = xnew; yprev = ynew; ynew += inc; } if (code == keyevent.vk_left){ xprev = xnew; yprev = ynew; xnew -= inc; } if (code == keyevent.vk_right){ xprev = xnew; yprev = ynew; xnew += inc; } graphics g = this.getgraphics(); g.setcolor(color.blue); g.drawline(xprev, yprev, xnew, ynew); } // not used required keylistener interface public void keyreleased (keyevent e) { } public void keytyped (keyevent e) { } }

this.requestfocusinwindow(); bad thought within paintcomponent method. painting should paint current state , never alter state of component getgraphics not how painting done in swing. custom painting should done within context of paintcomponent method. see painting in awt , swing , performing custom painting more details consider using key bindings on keylistener, can command focus level required trigger key events. see how utilize key bindings more details

remember, don't command paint process in swing, paint cycle can triggered number of events, of don't control. seek working within process instead of out of it.

start creating list of java.awt.point. add together each point list when key event occurs. utilize paintcomponent iterate on list , paint lines between points...

java swing paintcomponent

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -