Daniel Andrejczyk Daniel Andrejczyk - 15 days ago 4
Java Question

What is the difference and efficiency between main() and run()?

So I'm very new to the JSwing world, having not covered much in my AP Computer Science class I finished last year. So, I am familiar with inheritance and all the core parts of the Java language, but I can't see the difference between the two methods main() and run().

My code here works just fine for right now:

Main Class:



import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {

private JFrame frame;


public Main() {

frame = new JFrame("SoundCombine"); //Create frame

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Close the frame when |x| button is pressed

//Add components to the frame
JButton button = new JButton();
frame.getContentPane().add(button, BorderLayout.CENTER);

frame.pack();

frame.setVisible(true);
}

}





Run Class:



public class Run {

public static void main(String args[]){

new Main();

}

}





However, I've also seen this method of starting JSwing applications:



SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});





What is the big difference between the two? What sort of problems would I encounter down the road by using either one of the two. Although there are many different ways to write the same program, I want to know the conventional way of going about this.

Thanks!

Answer

You're asking what's the difference between an orange and a buffalo -- these are two completely different things.

  • The main method is the entry point of all Java programs, even those without main methods such as applets where there actually is a main method, but it's hidden from view.
  • The run method you speak of is a method that needs to be part of any class that implements a Runnable interface. This is not the entry point for programs to start.
  • Your example above, that is to feed a Runnable into the SwingUtilities.invokeLater(...) method is a way to guarantee that the code within the Runnable's run method is called on the Swing event thread, something that you want to do when starting Swing (not JSwing) applications for thread safety purposes, since if you don't do this, there are risks of errors (actually exceptions) being thrown.
  • Swing applications still need a main method regardless of whether you queue them on the Swing event thread or not. It's not "either use main or run", since again, they are totally different animals.
  • Just because some code "works for now" is no guarantee that it will work later. Threading exceptions are notorious for occurring intermittently and when least desired.
Comments