How to create and use button name(s) in Java

Hey all,

Is there a better way to create and name buttons on a controller instead of using something like this:

buttonValue = exampleStick.getRawButton(1);

Mainly just so it’s easier to read. Thanks for any help!

We created a class for our controller:

Usage here:

As Ty suggested, you can create your own class that extends the Joystick class to provide friendly references to the components of your controller. Here is a very simple, partial, example.

import edu.wpi.first.wpilibj.Joystick;

public class Gamepad extends Joystick {
	
	public Gamepad(int port) {
		super(port);
        }
	
	public boolean buttonA() {
		return this.getRawButton(1);
	}
	
	public boolean buttonB() {
		return this.getRawButton(2);
	}

	public double leftStickY() {
		return this.getRawAxis(1);
	}
}

Then in your main program you’d instantiate a “Gamepad” instead of a Joystick:

Gamepad gamepad = new Gamepad(0);

And reference the buttons like this:

if (gamepad.buttonA()) {
     // do something
}

Thank you for your responses. But what does the extends, this, and super mean? Thank you!

That’s the heritage notion, The class Joystick has been already created in the WPILIB, he just created a child class (name “Gamepad”) that can use all of the method that are in the class Joystick.

Here is the Java documentation on inheritance with a pretty good example: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html