| JButton |
|---|
This tutorial is now obsolete. Please see updated materials in the coreservlets.com Java programming tutorials. |
|---|
JButton are very similar to
Button. You create a JButton with a
String as a label, and then drop it in a window. Events
are normally handled just as with a Button: you attach an
ActionListener via the addActionListener method.
ImageIcon that lets you very easily specify an image file
(jpeg or GIF, including animated GIFs). Many Swing controls
allow the inclusion of icons. The simplest way to associate an image
with a JButton is to pass the ImageIcon to
the constructor, either in place of the text or in addition to
it. However, a JButton actually allows seven associated
images:
setIcon to specify it if not
supplied in the constructor),
setPressedIcon),
setRolloverIcon, but you need to call
setRolloverEnabled(true) first),
setSelectedIcon),
setDisabledIcon),
setDisabledSelectedIcon), and
setRolloverSelectedIcon).
You can also change the alignment of the text or icon in the button
(setHorizontalAlignment and
setVerticalAlignment; only valid if button is larger than
preferred size), and change where the text is relative to the icon
(setHorizontalTextPosition,
setVerticalTextPosition).
You can also easily set keyboard mnemonics via
setMnemonic. This results in the specified character
being underlined on the button, and also results in ALT-char
activating the button.
import java.awt.*;
import javax.swing.*;
public class JButtons extends JFrame {
public static void main(String[] args) {
new JButtons();
}
public JButtons() {
super("Using JButton");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JButton button1 = new JButton("Java");
content.add(button1);
ImageIcon cup = new ImageIcon("images/cup.gif");
JButton button2 = new JButton(cup);
content.add(button2);
JButton button3 = new JButton("Java", cup);
content.add(button3);
JButton button4 = new JButton("Java", cup);
button4.setHorizontalTextPosition(SwingConstants.LEFT);
content.add(button4);
pack();
setVisible(true);
}
}
Note: also requires
WindowUtilities.java
and ExitListener.java,
shown earlier, plus
cup.gif.