How to create an ActionListener in Swing GUI for racing game

In my game I am trying to use Swing GUI as I am more used to it than nifty. I used the code from the wiki page regarding using Swing GUI. My question is no matter what I try, I always get an error when I try to add an action listener to a JButton. Please help

Here is a picture of what I have

What is the error? where is the code that adds the listener? It’s hard for us to point you in a direction without at least those.

On another hand, have you taken a look at Lemur gui? It is designed to be very similar to swing but works within the jme scene graph.

I am assuming the error is the failure to compile? It seems you are trying to declare a method in the middle of another method, which will not work.

It appears you are very new to Java, many people will say learning to make a game is a terrible way to also learn Java, many people are probably right.
That said if you hit a roadblock you need to find a way to overcome it, so I’ll point you to the terms you’ll want to read up on.

You need to create an ActionListener object and assign it to your JButton. Here’s the java tutorial for buttons: How to Use Buttons, Check Boxes, and Radio Buttons (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)
and Action Listeners:
How to Write an Action Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)
It’s probably easier to make an anonymous ActionListener per button, at least that’s how I usually do it. Only after you can get the action listener to work should you look into Anonymous Classes but they are a nice shortcut to know about.

I don’t want to dissuade you from learning, but I would advise you to try making a stand alone, not jme related thing using swing before you try to use swing with jme. Making a simple Swing application that you can try creating and modifying your own classes in will be a better way to grasp Object Oriented coding than trying to work with Swing running on top of a Jme canvas.
Swing with Jme has a lot of overhead, threading issues and other annoying issues (swing tends to draw windows behind the jme canvas by default for example).

Use Lemur gui GitHub - jMonkeyEngine-Contributions/Lemur: Lemur is a jMonkeyEngine-based UI toolkit.. Lemur was designed to work inside JME in a very simple way, and the tutorials are pretty good for getting started. Lemur was designed to mimic Swing in alot of ways so it should be very familiar, except instead of attaching things to frames you’ll attach ui elements to a node in the jme scenegraph (usually the guiNode if you’re using SimpleApplication)

Lemur “Getting Started” documentation here:

An example game that uses it:

There are more complicated examples but that’s probably the most straight-forward GUI.

1 Like