Как сделать так, чтобы кнопка «Пуск» запускала игру? - PullRequest
0 голосов
/ 20 октября 2018

я делаю эту игру, и у меня есть меню, которое открывается первым при запуске программы, но кнопки меню ничего не делают.Как мне связать это окно меню с игрой, чтобы при нажатии «новая игра» игра начиналась?

PS Да, я пытался найти решение по нескольким видео на YouTube и собственному справочному сайту javas, но я не смог найтиКак связать действие нажатия кнопки, чтобы запустить действие в игре, чтобы оно в основном открыло игровой экран и запустило игру.

Будем признательны за любую помощь!

Код:

 public class Menu {
JTextArea output;
JScrollPane scrollPane;

public JMenuBar createMenuBar() {
    JMenuBar menuBar;
    JMenu menu, submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;

    //Create the menu bar.
    menuBar = new JMenuBar();

    //Build the first menu.
    menu = new JMenu("Menu");
    menu.setMnemonic(KeyEvent.VK_A);
    menu.getAccessibleContext().setAccessibleDescription(
            "The only menu in this program that has menu items");
    menuBar.add(menu);

    //a group of JMenuItems
    menuItem = new JMenuItem("New Game",
                             KeyEvent.VK_T);
    //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
            KeyEvent.VK_1, ActionEvent.ALT_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription(
            "This doesn't really do anything");
    menu.add(menuItem);

    ImageIcon icon = createImageIcon("");
    menuItem = new JMenuItem("Score history", icon);
    menuItem.setMnemonic(KeyEvent.VK_B);
    menu.add(menuItem);

    menuItem = new JMenuItem(icon);
    menuItem.setMnemonic(KeyEvent.VK_D);
    menu.add(menuItem);

    //a submenu
    menu.addSeparator();
    submenu = new JMenu("Options");
    submenu.setMnemonic(KeyEvent.VK_S);

    menuItem = new JMenuItem("Sounds");
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
            KeyEvent.VK_2, ActionEvent.ALT_MASK));
    submenu.add(menuItem);

    menuItem = new JMenuItem("Exit Game");
    submenu.add(menuItem);
    menu.add(submenu);

    //Build second menu in the menu bar.


    return menuBar;
}

public Container createContentPane() {
    //Create the content-pane-to-be.
    JPanel contentPane = new JPanel(new BorderLayout());
    contentPane.setOpaque(true);

    //Create a scrolled text area.
    output = new JTextArea(5, 30);
    output.setEditable(false);
    scrollPane = new JScrollPane(output);

    //Add the text area to the content pane.
    contentPane.add(scrollPane, BorderLayout.CENTER);

    return contentPane;
}

/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = Menu.class.getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}


private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("BlockBreaker");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    Menu demo = new Menu();
    frame.setJMenuBar(demo.createMenuBar());
    frame.setContentPane(demo.createContentPane());

    //Display the window.
    frame.setSize(450, 260);
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
}

Вот как я себе это представлял:

        menuItem.setAccelerator(KeyStroke.getKeyStroke(
            KeyEvent.VK_1, ActionEvent.ALT_MASK));
        menuItem.getAccessibleContext().setAccessibleDescription(
            "This doesn't really do anything");
        menu.add(menuItem);

        menuItem = new MouseAction(MouseEvent.PRESS_LMB)
            if (PRESS_LMB.menuItem("New Game")) {
                start Gameplay.java;
            }

Ответы [ 2 ]

0 голосов
/ 20 октября 2018
  • Используйте отдельное имя для разных игровых меню, иначе вы не сможете добавить к ним различные действия.
  • Действие, выполненное с использованием анонимного класса или ActionListener.Я показываю для анонимного класса.

См. Это для получения дополнительной информации: Как использовать JMenu

Использование анонимного класса:

final JMenuItem newGame;
newGame = new JMenuItem("New Game",
                         KeyEvent.VK_T);
menu.add(newGame);
newGame.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JFrame frame = new JFrame();
        frame.setSize(500, 100);
        frame.setTitle("Game on Fire");
        frame.show();
    }
});

Использование ActionListener:

public YourClass implements ActionListener, ItemListener {
@Override
public void actionPerformed(ActionEvent e) {
    //...Get information from the action event...
    //...Display it in the text area...
}
}

Если вы хотите запустить игру в том же окне, используйте JPanel внутри actionPerformed.Вот пример:

public class GameClass extends JPanel{
    ///Game Logic Here
}

затем добавьте это тоже ваше actionPerformed.

public void actionPerformed(ActionEvent e) {
    GameClass game = new GameClass();
    menuPanel.setVisible(false); /// menuPanel is a selection window.
    mainPanel.add(game); // Now add your Game Window to same Frame.     
}
0 голосов
/ 20 октября 2018

Используйте AbstractAction класс с вашим JMenuItem, как показано ниже.

Замените вашу строку кода:

menuItem = new JMenuItem("New Game", KeyEvent.VK_T);

На:

menuItem = new JMenuItem((new AbstractAction("New Game") {
    public void actionPerformed(ActionEvent e) {
        System.out.print("clicked");
    }
}));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...