JButton : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (all)

JButton
labeled push-button e.g. An OK button. In AWT (Advanced Windowing Toolkit) you use the Button class and in Swing the JButton.
Introduction Simulating a Button Click
Creating and Configuring a JButton Gotchas
JButton.setActionCommand Learning More
Hitting Enter Links
Focus Box

Introduction

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 JButton.

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 highlighting.

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

JButton.setActionCommand

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.

Hitting Enter

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.

Focus Box

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.
  1. Invoke the same appication method your JButton’s ActionListener does. This is the simplest if you know at compile time what the method is.
  2. Use JButton.doClick ().
  3. Use Robot.keyPress.
  4. Create a synthetic event and enqueue it.

Gotchas

Learning More

Oracle’s Javadoc on JButton class : available:
Oracle’s Javadoc on Robot.keyPress : available:

This page is posted
on the web at:

http://mindprod.com/jgloss/jbutton.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\jbutton.html
Canadian Mind Products
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.

IP:[65.110.21.43]
Your face IP:[18.208.203.36]
You are visitor number