I need some help with adding a menuBar to my JFrame. I have my GUI class:
public class Gui extends JFrame implements KeyListener {
private PanelMiniMap map;
private CardLayout cardLayout = new CardLayout();
private JPanel cards;
public Gui() {
this.setSize(1000, 800);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);// center
this.setResizable(false);
// bauen();
this.cards = new JPanel(cardLayout);
this.addListener();
this.add(cards);
this.setVisible(true);
}
public void addListener() {
this.addKeyListener(this);
}
public void addPanelZuCards(PanelSpielfeld spielfeld, PanelCharakterErschaffung charerschaffung, PanelMiniMap map) {
this.map = map;
this.cards.add(charerschaffung, "charerschaffung");
this.cards.add(spielfeld, "spielfeld");
}
public Dimension getDimension() {
return new Dimension(this.getWidth(), this.getHeight());
}
/**
* Neue Charaktererschaffung ausgeben
*
* @param charerschaffung
* Das Panel, auf dem die Oberflaeche zur Charaktererschaffung
* erstellt wird
*/
public void zeigeCharckterPanel() {
this.cardLayout.show(cards, "charerschaffung");
}
public void zeigeSpielPanel() {
this.cardLayout.show(cards, "spielfeld");
this.requestFocus();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
map.move(-1, 0);
map.repaint();
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
map.move(1, 0);
map.repaint();
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
map.move(0, -1);
map.repaint();
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
map.move(0, 1);
map.repaint();
}
}
}
where I add my 2 JPanels(PanelSpielfeld,PanelCharakterErschaffung)) to my GUI, and it locks like this:
and the other card, which is the same principle, I show the other card after pressing the "starten!" button:
So, if I add a menuBar to the Jframe:
public Gui() {
this.setSize(1000, 800);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);// center
this.setResizable(false);
// bauen();
this.cards = new JPanel(cardLayout);
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
menuBar = new JMenuBar();
menu = new JMenu("A Menu");
menuItem = new JMenuItem("testitem");
menu.add(menuItem);
menuItem = new JMenuItem("3214dx");
menu.add(menuItem);
menuItem = new JMenuItem("dwq213m");
menu.add(menuItem);
menuBar.add(menu);
this.add(menuBar);
this.addListener();
this.add(cards);
this.setVisible(true);
this.addWindowFocusListener(this);
}
Nothing is happening, and I don't really understand why. What am I doing wrong or what should I do, to have the same MenuBar on both "cards"?
Edit: I changed
this.add(menuBar)
to:
this.setJMenuBar(menuBar);
I'm still missing something. Do I have to set a specific LayoutManager for the JFrame?