Soup
Soup

Reputation: 1

My Buttons won't execute the command given to them

I am trying to get the buttons to at least execute something when they are pressed and BlueJ doesn't show any errors, but when I execute the Program and I try to press the buttons, nothing happens. I am really unsure why that is the case. I would appreciate any help!

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class MainMenu
{
JFrame frame= new JFrame();
JButton button = new JButton("Singleplayer");
JButton button2 = new JButton("Multiplayer");
MainMenu(){
    prepareGUI();
}  


public void prepareGUI(){
    frame.setTitle("Game");
    frame.getContentPane().setLayout(null);
    frame.add(button);
    frame.add(button2);
    button.setBounds(100,200,100,40);
    button2.setBounds(200,200,100,40);
    frame.setVisible(true);
    frame.setBounds(200,200,400,400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}


public void setUpButtonListeners(){
    ActionListener buttonlistener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.getContentPane().setBackground(Color.green);
                System.out.println("Singleplayer Selected");
            }
        };

    ActionListener buttonlistener2 = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                frame.getContentPane().setBackground(Color.red);
                System.out.println("Multiplayer Selected");
            }
        };
    button.addActionListener(buttonlistener);
    button2.addActionListener(buttonlistener2);
}
public class MainClass {
    public void main(String args[] )
    { 
        new MainMenu();
    }
}
}

Upvotes: 0

Views: 49

Answers (1)

cobp
cobp

Reputation: 772

setUpButtonListeners() are not executed in the program. So action listeners are not available. you can include setUpButtonListeners() in prepareGUI method.

Upvotes: 1

Related Questions