在程序中调用Main方法,Java

时间:2014-03-24 17:59:58

标签: java main

我有一个模拟足球的程序。当我在eclipse中正常运行Main类时,程序运行正常。我的问题是我想创建一个主菜单,它将调用Main方法并启动游戏。我有菜单,它调用方法,启动游戏,但不会将游戏画到屏幕上。这只发生在我从菜单启动游戏时,如果直接从Eclipse运行它可以正常工作。这是代码:

*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();
}

}*

主要课程:

/**
 * @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
}

}

当我按下"新游戏"按钮程序运行,但似乎跳过paint()方法,任何人都可以告诉我为什么会发生这种情况? 感谢

0 个答案:

没有答案