简体   繁体   中英

Button Click Action in Java

I am trying to make a game and right now and I need the buttons to have an action attached to the them when one is clicked but I keep getting an error saying "Syntax error, insert "}" to complete ClassBody" there is not an error of a missing "}" however so there must be a problem with the code itself.

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Menu extends Window implements ActionListener
{

  Button start = new Button("Start Game:");
  Button quit = new Button("Quit");
}


public void actionPerformed(ActionEvent e)
{
  if (e.getActionCommand().equals("Start Game: "))
{
  System.out.print("Button one clicked");
}
else if (e.getActionCommand().equals("Quit"))
{
  System.out.print("Button two clicked");
}


}

Method onActionPerformed is not in a class block:

public class Menu extends Window implements ActionListener
{ //Class block starts

  Button start = new Button("Start Game:");
  Button quit = new Button("Quit");
} //Class block ends

public void actionPerformed(ActionEvent e)
....

All ethods of a class must be inside the block of the class:

public class Menu extends Window implements ActionListener {

    Button start = new Button("Start Game:");
    Button quit = new Button("Quit");

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Start Game: ")) {
            System.out.print("Button one clicked");
        } else if (e.getActionCommand().equals("Quit")) {
            System.out.print("Button two clicked");
        }

    }
}

Also, you might have to decide if you are going to use AWT widgets ( java.awt.* ) or Swing Components ( javax.swing.* ).

For instance, when you say Button button = new Button(); , its an AWT widget. In order to use the Swing one, you must JButton jButton = new JButton(); .

You forgot to register an instance of the event handler class as a listener on the button.

Add this inside your class

start.addActionListener(this);
quit.addActionListener(this);

Also you have to move the actionPerformed function inside class body. Your class will look like

public class Menu extends Window implements ActionListener
{

  Button start = new Button("Start Game:");
  Button quit = new Button("Quit");
  start.addActionListener(this);
  quit.addActionListener(this);

 public void actionPerformed(ActionEvent e)
{
  if (e.getActionCommand().equals("Start Game: "))
  {
    System.out.print("Button one clicked");
  }
  else if (e.getActionCommand().equals("Quit"))
  {
    System.out.print("Button two clicked");
  }    
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM