• Post Reply Bookmark Topic Watch Topic
  • New Topic

How is it that some methods like paint( ) are called automatically?  RSS feed

 
John Quach
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
methods like run () for threads and paint ( ) for GUIs.
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you start a Thread? By calling its start() method - And the start() method makes the JVM call the run() method in turn. Read Thread:start()
 
John Quach
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that. But is it possible to call methods like that using your own classes?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Quach wrote:I know that. But is it possible to call methods like that using your own classes?


Why not? How it different than just calling any other method in your code?


Now, having said that, the start() method does abstract it a bit by using the Runnable interface. This way, the method doesn't need to know the full details of the class being passed in, it just needs to know about the run() method, which is part of the Runnable interface.

Henry
 
John Jai
Rancher
Posts: 1776
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adding to that when you call the run() method directly it's like executing any other method from your main thread. No thread is started.

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Those methods are not really called "automatically", they are called by other classes in the JVM as the result of you calling some other method in the JVM (for example, when you call start() on a Thread, the JVM will call run() on the Runnable that you've provided for the thread). Likewise, when you call repaint() on a GUI component, then paint() will be called by the JVM on that component a little while later.

And ofcourse you could call those methods directly, because they're just methods, exactly the same as other methods. But often you do not want to call them directly, because they'll not work like you intended - for example of you call run() on a Runnable directly, then no new thread will be started, the method will just run in the current thread, and if you call paint() directly, you're likely to get an exception or other strange things might happen to your GUI, because Swing requires that painting GUI components happens on the Swing event dispatch thread.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!