0

I have a program that simulates football. When I run the Main class normally in eclipse the program runs fine. My problem is that I want to create a main menu that will call the Main method and start the game. I have the menu made and it calls the method, starts the game but does not draw the game to the screen. This only happens when I start the game from the menu, if ran directly from Eclipse it works fine. Here is the code:

*package SimpleSoccer;

//imports removed

/**
 * Class to show main menu and give options to view stats, start new game, or exit
 *
 *
 */
public class MainMenu extends JFrame {
//constructor
MainMenu() {

    super("Main Menu for Soccer Simulator");

    setSize(400, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container content = getContentPane();

    content.setBackground(Color.green);
    content.setLayout(new FlowLayout());

    JButton startGame = new JButton("Start Game");
    content.add(startGame);
    startGame.addActionListener(new ButtonListener());

    JButton viewStats = new JButton("View Stats");
    content.add(viewStats);
    viewStats.addActionListener(new ButtonListener2());


    JButton exit = new JButton("Exit");
    content.add(exit);
    exit.addActionListener(new ButtonListener3());


    setVisible(true);
}

//for the start game button
//Main m = new Main();
class ButtonListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent a) {
        Main.main(null);

    }
}

//for the view stats button
class ButtonListener2 implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent a) {
        StatTable.main(null);
    }
}


//for the exit button
class ButtonListener3 implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent a) {
        System.exit(0);
    }
}

public static void main(String[] args) {
    MainMenu m = new MainMenu();
}

}*

The Main class:

/**
 * @author Petr (http://www.sallyx.org/)
 */
package SimpleSoccer;
*emphasized text*
//imports removed

public class Main {
//--------------------------------- Globals ------------------------------
//
//------------------------------------------------------------------------

static String g_szApplicationName = "Simple Soccer";
//static String g_szWindowClassName = "MyWindowClass";
static SoccerPitch g_SoccerPitch;
// bacause of game restart (g_SoccerPitch could be null for a while)
static Lock SoccerPitchLock = new ReentrantLock();
//create a timer
static PrecisionTimer timer = new PrecisionTimer(Prm.FrameRate);

//used when a user clicks on a menu item to ensure the option is 'checked'
//correctly
static void CheckAllMenuItemsAppropriately(MyMenuBar hwnd) {
    CheckMenuItemAppropriately(hwnd, IDM_SHOW_REGIONS, Prm.bRegions);
    CheckMenuItemAppropriately(hwnd, IDM_SHOW_STATES, Prm.bStates);
    CheckMenuItemAppropriately(hwnd, IDM_SHOW_IDS, Prm.bIDs);
    CheckMenuItemAppropriately(hwnd, IDM_AIDS_SUPPORTSPOTS, Prm.bSupportSpots);
    CheckMenuItemAppropriately(hwnd, ID_AIDS_SHOWTARGETS, Prm.bViewTargets);
    CheckMenuItemAppropriately(hwnd, IDM_AIDS_HIGHLITE, Prm.bHighlightIfThreatened);
}

static void HandleMenuItems(int wParam, MyMenuBar hwnd) {
    switch (wParam) {
    case ID_AIDS_NOAIDS:

        Prm.bStates = false;
        Prm.bRegions = false;
        Prm.bIDs = false;
        Prm.bSupportSpots = false;
        Prm.bViewTargets = false;
        Prm.bHighlightIfThreatened = false;

        CheckAllMenuItemsAppropriately(hwnd);

        break;

    case IDM_SHOW_REGIONS:

        Prm.bRegions = !Prm.bRegions;

        CheckAllMenuItemsAppropriately(hwnd);

        break;

    case IDM_SHOW_STATES:

        Prm.bStates = !Prm.bStates;

        CheckAllMenuItemsAppropriately(hwnd);

        break;

    case IDM_SHOW_IDS:

        Prm.bIDs = !Prm.bIDs;

        CheckAllMenuItemsAppropriately(hwnd);

        break;


    case IDM_AIDS_SUPPORTSPOTS:

        Prm.bSupportSpots = !Prm.bSupportSpots;

        CheckAllMenuItemsAppropriately(hwnd);

        break;

    case ID_AIDS_SHOWTARGETS:

        Prm.bViewTargets = !Prm.bViewTargets;

        CheckAllMenuItemsAppropriately(hwnd);

        break;

    case IDM_AIDS_HIGHLITE:

        Prm.bHighlightIfThreatened = !Prm.bHighlightIfThreatened;

        CheckAllMenuItemsAppropriately(hwnd);

        break;

    }//end switch
}
static BufferedImage buffer;
static Graphics2D hdcBackBuffer;
//these hold the dimensions of the client window area
static int cxClient;
static int cyClient;

long tStart = System.currentTimeMillis();
long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;

long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec

public static void main(String[] args) {


    final Window window = new Window(g_szApplicationName);
    window.setIconImage(LoadIcon("/SimpleSoccer/icon1.png"));
    window.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    buffer = new BufferedImage(WindowWidth, WindowHeight, BufferedImage.TYPE_INT_RGB);
    hdcBackBuffer = buffer.createGraphics();
    //these hold the dimensions of the client window area
    cxClient = buffer.getWidth();
    cyClient = buffer.getHeight();
    //seed random number generator
    common.misc.utils.setSeed(0);

    window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
    //Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();

    window.setResizable(false);

    int y = center.y - window.getHeight() / 2;
    window.setLocation(center.x - window.getWidth() / 2, y >= 0 ? y : 0);
    Script1.MyMenuBar menu = Script1.createMenu(IDR_MENU1);
    window.setJMenuBar(menu);

    g_SoccerPitch = new SoccerPitch(cxClient, cyClient);

    CheckAllMenuItemsAppropriately(menu);


    final JPanel panel = new JPanel() {

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            gdi.StartDrawing(hdcBackBuffer);
            //fill our backbuffer with white
            gdi.fillRect(Color.WHITE, 0, 0, WindowWidth, WindowHeight);
            SoccerPitchLock.lock();
            g_SoccerPitch.Render();
            SoccerPitchLock.unlock();
            gdi.StopDrawing(hdcBackBuffer);
            g.drawImage(buffer, 0, 0, null);
        }
    };
    panel.setSize(WindowWidth, WindowHeight);
    panel.setPreferredSize(new Dimension(WindowWidth, WindowHeight));
    window.add(panel);
    window.pack();

    window.addKeyListener(new KeyAdapter() {

        @Override
        public void keyReleased(KeyEvent e) {
            CppToJava.keyCache.released(e);
            switch (e.getKeyChar()) {
            case KeyEvent.VK_ESCAPE: {
                System.exit(0);
            }
            break;
            case 'r':
            case 'R': {
                SoccerPitchLock.lock();
                g_SoccerPitch = null;
                g_SoccerPitch = new SoccerPitch(cxClient, cyClient);
                JMenuBar bar = Script1.createMenu(IDR_MENU1);
                window.setJMenuBar(bar);
                bar.revalidate();
                SoccerPitchLock.unlock();
            }
            break;

            case 'p':
            case 'P': {
                g_SoccerPitch.TogglePause();
            }
            break;

            }//end switch
        }//end switch        }

        @Override
        public void keyPressed(KeyEvent e) {
            CppToJava.keyCache.pressed(e);
        }
    });

    window.addComponentListener(new ComponentAdapter() {

        @Override //has the user resized the client area?
        public void componentResized(ComponentEvent e) {
            //if so we need to update our variables so that any drawing
            //we do using cxClient and cyClient is scaled accordingly
            cxClient = e.getComponent().getBounds().width;
            cyClient = e.getComponent().getBounds().height;
            //now to resize the backbuffer accordingly. 
            buffer = new BufferedImage(cxClient, cyClient, BufferedImage.TYPE_INT_RGB);
            hdcBackBuffer = buffer.createGraphics();
        }
    });

    //make the window visible
    window.setVisible(true);

    //timer.SmoothUpdatesOn();

    //start the timer
    timer.Start();

    while (true) {
        //update
        if (timer.ReadyForNextFrame()) {
            SoccerPitchLock.lock();
            g_SoccerPitch.Update();
            SoccerPitchLock.unlock();
            //render
            //panel.revalidate();
            panel.repaint();

            try {
                //System.out.println(timer.TimeElapsed());
                Thread.sleep(2);
            } catch (InterruptedException ex) {
            }
        }
    }//end while
}

}

When I press the "New Game" button the program runs but seems to skip the paint() method, can anyone tell me why this is happening? Thanks

SAF
  • 81
  • 2
  • 2
  • 7
  • 1
    Is it just the image that you load up from the file system that is missing? Because I've run into that before too. Eclipse has one file path for referencing images relative to the project, but if you actually run the program from the command line, it is not using the same path. So you have to address that situation somehow. Also you have to watch this same thing when you package the program as a jar. Image files will be mysteriously gone, but it all goes back to relative file paths. – Scott Shipp Mar 24 '14 at 18:06
  • Have you tried overriding paintComponent() instead of paint()? see [link](http://stackoverflow.com/questions/9389187/difference-between-paint-paintcomponent-and-paintcomponents-in-swing) – nbsp Mar 24 '14 at 18:07
  • no the whole program is drawn using methods from Java, there are no images except for the soccer ball in the corner of the window. I don't understand this at all, it runs fine when I click "run" in eclipse but when I call the main method it skips the paint method in Main.. – SAF Mar 24 '14 at 18:08
  • Tried using paintComponent() there, it threw up a ton of errors, thanks though – SAF Mar 24 '14 at 18:11

0 Answers0