Jmenuitems кнопки не отвечают - PullRequest
0 голосов
/ 11 марта 2020

Я создал игру памяти 3х3 с цветами. Программа запускается и отображает цвета, но Jmenubar работает неправильно. Кнопка new board, play и end game не работают. Что-то не так с моим Actionlistener?

Вот как должен работать код: https://gyazo.com/9bf3e073a9c455e56d9b4403586bfaf5?fbclid=IwAR3Zk1BZvRj49CtAz01h95zic8tk74UmyUcU2HrY3VY8XcARoD14Ke6tcoQ

--This is StartPlayer.java

import gui.MemoryGameWindow;
import gui.ColoredPanel;
import gui.GamePanel;

public class StartPlayer {
  public static void main(String[] args) {
  new MemoryGameWindow();

}
}



--This is ColoredPanel.java
package gui;

import java.awt.Color;
import java.awt.event.MouseListener;
import javax.swing.JPanel;

public class ColoredPanel extends JPanel {
  private Color thisColor = null;

  private Color challenge = null;

  public ColoredPanel(Color color) {
    this.thisColor = color;
    setBackground(color);
  }

  public void setGameMode(Color c, MouseListener ml) {
    setBackground(Color.LIGHT_GRAY);
    this.challenge = c;
    System.out.println("Coloredpanel says challenge is " + this.challenge);
    addMouseListener(ml);
  }

  public void restoreBackground() {
    setBackground(this.thisColor);
  }
}



-- This is GamePanel.java
package gui;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GamePanel extends JPanel {
  private Color[] colors = new Color[] { Color.GREEN, Color.YELLOW, Color.MAGENTA };

  private Random r = new Random();

  private int square = 9;

  private Color challenge;

  private int countOfPossibleHits = 0;

  private int countOfWinnerHits = 0;

  private JPanel challengeDisplay;

  public GamePanel(JPanel cd) {
    this.challengeDisplay = cd;
    setLayout(new GridLayout(3, 0, 2, 2));
    for (int i = 0; i < this.square; i++)
      add(new ColoredPanel(this.colors[this.r.nextInt(this.colors.length)])); 
  }

  public Color startGame() {
    Color[] existingColors = new Color[getComponentCount()];
    int i;
    for (i = 0; i < getComponentCount(); i++)
      existingColors[i] = ((ColoredPanel)getComponent(i)).getBackground(); 
    this.challenge = existingColors[this.r.nextInt(existingColors.length)];
    this.countOfPossibleHits = 0;
    for (i = 0; i < getComponentCount(); i++) {
      if (((ColoredPanel)getComponent(i)).getBackground() == this.challenge)
        this.countOfPossibleHits++; 
    } 
    for (i = 0; i < getComponentCount(); i++)
      ((ColoredPanel)getComponent(i)).setGameMode(this.challenge, new TheMouselistener()); 
    return this.challenge;
  }

  class TheMouselistener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
      ColoredPanel clickedObject = (ColoredPanel)e.getSource();
      clickedObject.restoreBackground();
      if (clickedObject.getBackground() != GamePanel.this.challenge) {
        clickedObject.add(new JLabel("Game Over!"));
        GamePanel.this.challengeDisplay.add(new JLabel("Game Over!"));
        System.out.println("Game Over");
        GamePanel.this.updateUI();
      } else {
        GamePanel.this.countOfWinnerHits = GamePanel.this.countOfWinnerHits + 1;
        if (GamePanel.this.countOfWinnerHits == GamePanel.this.countOfPossibleHits) {
          clickedObject.add(new JLabel("You won!"));
          GamePanel.this.challengeDisplay.add(new JLabel("You Won!"));
          GamePanel.this.updateUI();
        } 
      } 
    }
  }
}

--This is MemoryGameWindow.java
package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class MemoryGameWindow extends JFrame implements ActionListener {
  private JMenuItem newgame = null;

  private JMenuItem playgame = null;

  private JMenuItem exit = null;

  private GamePanel gamepanel = null;

  private JPanel challengeDisplay;

  public MemoryGameWindow() {
    setTitle("memory game");
    setLayout(new BorderLayout(5, 5));
    add(this.challengeDisplay = new JPanel() {

        },  "North");
    add(this.gamepanel = new GamePanel(this.challengeDisplay));
    setJMenuBar(new GameMenubar(this));
    setSize(600, 600);
    setLocationRelativeTo((Component)null);
    setVisible(true);
  }

  public void actionPerformed(ActionEvent e) {
    Object s = e.getSource();
    if (s == this.newgame) {
      remove(this.gamepanel);
      remove(this.challengeDisplay);
      add(this.challengeDisplay = new JPanel() {

          },  "North");
      add(this.gamepanel = new GamePanel(this.challengeDisplay));
      this.playgame.setEnabled(true);
      this.gamepanel.updateUI();
    } 
    if (s == this.playgame) {
      Color challenge = this.gamepanel.startGame();
      this.challengeDisplay.setBackground(challenge);
      this.playgame.setEnabled(false);
      this.gamepanel.updateUI();
    } 
    if (s == this.exit)
      System.exit(0); 
  }

  class GameMenubar extends JMenuBar {
    public GameMenubar(MemoryGameWindow memoryGameWindow) {
      JMenu file;
      add(file = new JMenu("File"));
      MemoryGameWindow.this.newgame = new JMenuItem("new board");
      file.add(new JMenuItem("new board"));
      MemoryGameWindow.this.playgame = new JMenuItem("play");
      file.add(new JMenuItem("play"));
      MemoryGameWindow.this.exit = new JMenuItem("end program");
      file.add(new JMenuItem("end program"));
      MemoryGameWindow.this.newgame.addActionListener(memoryGameWindow);
      MemoryGameWindow.this.playgame.addActionListener(memoryGameWindow);
      MemoryGameWindow.this.exit.addActionListener(memoryGameWindow);


    }
  }
}

1 Ответ

0 голосов
/ 11 марта 2020

Посмотрите на эти две строки:

MemoryGameWindow.this.playgame = new JMenuItem("play");
file.add(new JMenuItem("play"));

Сначала вы устанавливаете значение playgame для нового JMenuItem. Позже в коде вы добавляете ActionListener к нему. Это все правильно.

Проблема в том, что JMenuItem с добавленным в него ActionListener - это не то, что вы добавляете в строку меню. Вместо этого вы добавляете совершенно новый JMenuItem, к которому не добавлены ActionListeners.

Исправление так же просто, как:

file.add(MemoryGameWindow.this.playgame);

Очевидно, вы нужно будет сделать это и для других пунктов меню.

...