

InterviewSolution
1. |
Solve : java working unexpectedly? |
Answer» I want the cyan rectangle to move but it don't. EventQueue.invokeLater(new Runnable() {* MAYBE this is correct for Java syntax, but I am use to seeing a function called that is independent of being enclosed within ( ...... ); multilines, and not structured how you have it with everything contained within a spanned multiline ( ...... ); as I highlighted. I don't program in Java so this may be valid syntaxWell it doesn't show anything as is. I had to change the paint method to get them to show up at all: Code: [Select]public void paint(Graphics frame){ System.out.println("paint"); //super.paint(frame); Rectangle clip = frame.getClipBounds(); frame.clearRect(clip.x,clip.y,clip.width,clip.height); frame.setColor(Color.CYAN); frame.fill3DRect(r1.x, r1.y, r1.width, r1.height,true); frame.setColor(Color.BLUE); frame.fill3DRect(r2.x, r2.y, r2.width, r2.height,true); } The cyan rectangle (r1) doesn't move because the move() method is never called. add move(); before repaint() in the run method. Quote from: DaveLembke on March 05, 2013, 05:04:41 PM * Maybe this is correct for Java syntax, but I am use to seeing a function called that is independent of being enclosed within ( ...... ); multilines, and not structured how you have it with everything contained within a spanned multiline ( ...... ); as I highlighted. It's correct. In fact, the original code could be refactored to completely eliminate move1. right now they are subclassing Thread. this is bad. Don't do this. First, what they ought to be doing is creating a class that implements Runnable, and passing an instance of that class to the Thread constructor. Thread should only be subclassed if you want to add new Thread functionality, not to implement the Run method. Right now: Code: [Select]Thread move1 = new Move1(); My version: Code: [Select]Thread move1 = new Thread(new Runnable() {public void run(){ //infinite loop while(true) { try { move(); //invalidate(); repaint(); Thread.sleep(100); } catch(Exception e) { break; } }}}); This BASICALLY moved the implementation within the class they had that derived from Thread to here. to explain more simply the part that got you confused: that would be the anonymous interface implementation feature of Java. In this case, it's implementing Runnable. A simple example: Code: [Select]private void somemethod(Runnable runner){ runner.run(); } private void main(String[] args){ somemethod(new Runnable(){ public void run(){System.out.println("howdy!");} } ); } (Not formatted well). basically, you can use new with an interface type and define the interface implementation in-line. The DOCUMENTATION is perhaps a more heady source of information. |
|