I am trying to create a basic game menu for a game right now. I am just testing out the menu for now, and most of the options I wrote are just to test out whether the menu actually works or not. So I have a Menu class and a OptionPanel class as well.
Here is the Menu Class:
import java.awt.event.*; import javax.swing.*; import java.awt.*; public class Main extends JFrame { JPanel cardPanel; public Main(String title) { super(title); setBounds(100, 100, 800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cardPanel = new JPanel(); CardLayout cl = new CardLayout(); cardPanel.setLayout(cl); OptionPanel panel1 = new OptionPanel(this); Board panel2 = new Board(); Rules panel3 = new Rules(); cardPanel.add(panel1,"1"); cardPanel.add(panel2,"2"); cardPanel.add(panel3,"3"); add(cardPanel); setVisible(true); } public static void main(String[] args) { Main w = new Main("AP Animation Demo"); } public void changePanel() { ((CardLayout)cardPanel.getLayout()).next(cardPanel); requestFocus(); } } And here is my Option Panel class:
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class OptionPanel extends JPanel implements ActionListener { Main w; public OptionPanel(Main w) { this.w = w; JButton button = new JButton("Press me!"); button.addActionListener(this); add(button); JButton button2 = new JButton("Game rules"); button2.addActionListener(this); add(button2); } public void paintComponent(Graphics g) { super.paintComponent(g); setBackground(Color.BLACK); }// Call JPanel's paintComponent method to paint the background public void actionPerformed(ActionEvent e) { w.changePanel(); } } How do I make it so when the menu pops up, I can click on one button that leads to the game, and when clicking on another button, get linked to another screen. I think it has something to do with the actionPerformed thing, so I tried adding if (e.getSource == button) and stuff like that, but it could not find any button variable. Any advice/feedback?
paintComponent(Graphics)does, remove it and putsetBackground(Color.BLACK);in the constructor.