I´m making a simple application in which there are a menu-screen and a game-screen. In the menu-screen there are a go-button and if you click it with the mouse the menu-screen switches to the game-screen, in which there are some simple gameplay.
The main class (it extends JFrame) ma开发者_运维百科nages the screen switching and sets up the screens through cardlayout. It sets up a JFrame and a JPanel called cardpanel on it. Cardpanel then adds:
cardPanel.add(menu, "menuscreen");
cardPanel.add(game, "gamescreen");
menu and game are references to their classes (the classes extends JPanel).
The issue is that when I try to add the JPanel p, which is registered to a mouselistener, in the menu, nothing happens when clicking on it. I tried to add p directly into the main class and it worked since menu is the default visible screen, but when switching to game-room, the users keyboard inputs didn´t work. And when the game-screen was the default one, and p was added directly into main, the inputs did not work. So I really have to add p into the menu-screen, plus, it makes the code look better.
Thankful for help and advices!
Here is the menu class code, in which I have tried to add p: (deleted irrelevant drawing)
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Menu extends JPanel implements ActionListener, MouseListener, Commons{
public static int points = 0;
public int xMouse;
public int yMouse;
private Timer timer;
private Image image;
private String backMenu = "backMenu.png";
private Go go;
private Logo logo;
JPanel p = new JPanel();
public Main main;
public Menu(Main main){
add(p);
this.main = main;
timer = new Timer(5, this);
timer.start();
ImageIcon ii = new ImageIcon(getClass().getResource(backMenu));
image = ii.getImage();
go = new Go();
logo = new Logo();
setVisible(true);
setFocusable(true);
p.addMouseListener(this);
p.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
repaint();;
}
@Override
public void mouseClicked(MouseEvent e) {
if ((e.getX() > go.getX()) && (e.getX() < go.getX()+go.getWidth())){
if ((e.getY() > go.getY()) && (e.getY() < go.getY()+go.getHeight()))
{
main.changeScreen();
}
}
}
}
精彩评论