I'm trying to create a program in Java that I have in C++. In my C++ file, I have main the main method outside of any classes. Eclipse does not seem to like this. Is this not possible in Java? Do I need to put main in a class?

import javax.swing.*;
import java.awt.Color;
import java.awt.event.*;

class ExampleProgram extends JFrame {

  public ExampleProgram(){
    String text = new String("I'm a simple Program ");
    String text2 = text.concat(
      "that uses classes and objects");

    JLabel label = new JLabel(text2);
    JPanel panel = new JPanel();
    panel.setBackground(Color.white);

    getContentPane().add(panel);
    panel.add(label);
  }

  public static void main(String[] args){
    ExampleProgram frame = new ExampleProgram();

    frame.setTitle("Fruit $1.25 Each");
    WindowListener l = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    };

    frame.addWindowListener(l);
    frame.pack();
    frame.setVisible(true);
  }
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Java will not accept a method that is not part of a class. The only things that have methods are classes and objects (classes have static methods, like

public static void main (String args[])

and objects have instance methods like

public String toString()

That's the way it is. Why not put the main method in the class? Should work fine.

This article has been dead for over six months. Start a new discussion instead.