JButton : Java Glossary
©1996-2017 2008-02-24 Roedy Green of Canadian Mind Products
labeled push-button e.g. An OK button. In AWT (Advanced Windowing Toolkit)
you use the Button class and in Swing the JButton.
Putting \n in the
Button’s label text won’t give you a multiline
label. You must use a javax.swing. JButton. You feed it HTML (Hypertext Markup Language)
containing a <br>. Similarly if you want to
decorate your buttons with images, or you want non-rectangular buttons, you must use
Even when you use a round button image, it still lives on a rectangular
transparent background. This means if the user clicks in the transparent corners, it
still counts as clicking the button. It also counts for the rollover button
If you did a setLayout ( null ); you could absolutely position your buttons so they
overlapped slightly in the transparent corners. This would let you pack the buttons
more closely than the surrounding rectangles would naturally allow.
Creating and Configuring a JButton
The JButton.setActionCommand does not set up an ActionListener. It simply records a string you may retrieve later
with getActionCommand. It just helps you remember what to
do in the ActionListener when that button is pressed.
It helps you sort of which button was pressed and just what you are supposed to do
about it. Alternatively, you can hide information with setName, though I normally use that for debugging field names,
automatic label generation, or prompting information. To hide binary data, put a
16-bit unsignd number in the first char of the String.
Windows users are used to hitting Enter instead of
clicking a button, if the button has focus. This does not always work. If you are
using the Metal look and feel, you need to press space instead.
Swing paints a thin box on a button if it has focus.
You can suppress that with:
theButton.setFocusPainted( false );
Simulating a Button Click
Here are four methods so simulate the
user clicking a JButton.
- Invoke the same appication method your JButton’s ActionListener does.
This is the simplest if you know at compile time what the method is.
- Use JButton.doClick
- Use Robot.keyPress.
- Create a synthetic
event and enqueue it.
will not work if you combine it with JButton.
setBorder. That is because setMargin is implemented as a Border.
Use a compound Border to get extra space around the text
and a decorative border. See the example code for how.
- If the JButtons are too small, fluff them up with
setMargin or with the ipadx
and ipady GridBagLayout
Oracle’s Javadoc on JButton
class : available:
Oracle’s Javadoc on Robot.keyPress