Example 06 – Interactive JButton

Another lesson from learn by examples, today we have a simple gui with a couple of interact JButton(s), the whole reason you may want to do this is for a bit of eye candy, make it look good.

The first button we have listed bellow will not have any instruction, so clicking won’t do anything but what it does is every time you hover over it changes the colour and the text, when you hover away it will once again change the colour and the text. All the code is available at the full source code listed below.

final JButton colorButton = new JButton( "Hover Over");

The second button is another interesting one as we will apply a new rounded shape to the button when we click on it, this is only a simple example but can give you some great ideas in different shapes, colours, text, formats or anything you want every time someone presses the button.

So for this button I had to create a additional class that will apply the button when you call it.

This code will allow us to change the shape of the button when used.


class RoundedBorder implements Border {
int radius;
RoundedBorder(int radius) {
this.radius = radius;
}
public Insets getBorderInsets(Component c) {
return new Insets(this.radius+1, this.radius+1, this.radius+2, this.radius);
}
public boolean isBorderOpaque() {
return true;
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
g.drawRoundRect(x,y,width-1,height-1,radius,radius);
}
}

The last button is just an exit button, nothing special and nothing fancy if you click it will close your SimpleGUI

So here is the example of what the code will allow you to create.

blog-lesson06

For the full source code view here SimpleGUI-Lesson6