Question

I am new to Java, so please bear with me. I've tried to get a button to open up a new frame called AboutFrame, but whenever I press the button nothing happens.

I implement the ActionListener first:

class MainFrame extends JFrame implements ActionListener {

Then I set the button (after the usual super("blabla");...)

JButton info = new JButton("About Failsafe");
    info.addActionListener(this);

And then:

public void actionPerformed(ActionEvent event) {
String command = event.getSource().toString();
    if (command == "info") {
        AboutFrame abt = new AboutFrame();
    }
}

So what am I doing wrong here? I can't see any mistakes..

Was it helpful?

Solution

You're not getting the command text correctly:

JButton button = (JButton) event.getSource();
String command = button.getText();

if (command.equals("About Failsafe"))
{
  AboutFrame abt = new AboutFrame();
  abt.setVisible(true);
}

Or, if your JButton info; declaration is an instance variable (instead of a local one), you could make your if-check:

if (event.getSource() == info)

OTHER TIPS

Try:

if (event.getSource()==info) {}

instead of if (command=="info") {}.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top