Comp Sci Why does this method execute? JAVA

  • Thread starter Thread starter TheMathNoob
  • Start date Start date
  • Tags Tags
    Java Method
AI Thread Summary
In Java Swing applications, the paint method is automatically invoked by the Swing thread when a component needs to be rendered, even though it is not explicitly called in the main method. This behavior allows the GUI to remain responsive while the main thread handles other tasks. The separation of threads ensures that long-running computations do not freeze the user interface, enabling user interactions like closing the application. The discussion highlights the importance of understanding thread management in Java GUI programming. Overall, this mechanism enhances the user experience by maintaining a responsive interface during background processing.
TheMathNoob
Messages
189
Reaction score
4

Homework Statement


Java:
package myfirstgame;
import javax.swing.JFrame;
import java.awt.Graphics;
/**
*
* @author danif
*/
public class MyFirstGame extends JFrame {

  public MyFirstGame()
  {
      setTitle("the game");
      setSize(250,250);
      setResizable(false);
      setVisible(true);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    
  }
  public void paint(Graphics g)
  {
      g.draw3DRect(WIDTH, WIDTH, WIDTH, WIDTH, rootPaneCheckingEnabled);
  }
    public static void main(String[] args) {
      
        MyFirstGame game = new MyFirstGame();
    }
  
}

Homework Equations

The Attempt at a Solution



It is kind of weird to me how paint executes without calling the function in the main. As soon as the object is created, paint is called. But paint is not static, so it is weird.
 
Last edited by a moderator:
Physics news on Phys.org
When this kind of java program is run, the java runtime starts two threads a main thread and a swing thread. You're seeing the swing thread in operation. The idea is that your actual work is done in the main thread while at the same time the program GUI stays responsive to the enduser.

As an example, if you wrote a program to display a julia set fractal, then the enduser can interact with the program (like press the exit icon) while the program is computing the fractal points and periodically calling the repaint() method to have the swing thread update the screen display.

http://www.oracle.com/technetwork/java/painting-140037.html
 
Last edited by a moderator:

Similar threads

Replies
1
Views
2K
Replies
2
Views
1K
Replies
12
Views
2K
Replies
5
Views
3K
Replies
1
Views
2K
Replies
7
Views
2K
Replies
9
Views
2K
Replies
0
Views
322
Back
Top