JButton Example
This JButton example adds a JButton to a JFrame. In common with many other Swing components the first letter of the JButton component begins with J.
JButtons can be pressed and are provided in interfaces to enable users to cause something to happen.
The button in this example can be pressed but it doesn't do anything ... but see the ActionListener example to the left.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// JButton Example
import javax.swing.*;
class JButtonExample {
public static void main(String[] args) {
JFrame jframe = new JFrame();
JButton jButton = new JButton("target");
jframe.getContentPane().add(jButton);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}
}
10 A JButton is created.
The parameter is the string text that will appear on the button. The possble constructors are:
JButton() JButton(Action a) JButton(Icon icon) JButton(String text) JButton(String text, Icon icon)which shows that icons can also be used.
12 The JButton is added to the JFrame's contentPane.
If this line is omitted the JButton will not be visible.
14 The JFrame.pack() method causes the JFrame to be sized to fit the components in it.
Each component added to a JFrame has a preferred size which is dependent on various factors, such as in this case the width and height of the text on the face of the button.
Preferred sizes are taken into account by the JFrame.pack() method.
