Making a button
Making a button is quite simple: you just call the JButton constructor with the label you want on the button. You’ll see later that you can do fancier things, like putting graphic images on buttons.
Usually, you’ll want to create a field for the button inside your class so that you can refer to it later.
The JButton is a component—its own little window—that will automatically get repainted as part of an update. This means that you don’t explicitly paint a button or any other kind of control; you simply place them on the form and let them automatically take care of painting themselves. So to place a button on a form, you do it inside init( ):
//: c14:Button1.java
// Putting buttons on an applet.
// <applet code=Button1 width=200 height=50></applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class Button1 extends JApplet {
private JButton
b1 = new JButton("Button 1"),
b2 = new JButton("Button 2");
public void init() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b1);
cp.add(b2);
}
public static void main(String[] args) {
Console.run(new Button1(), 200, 50);
}
} ///:~
Something new has been added here: Before any elements are placed on the content pane, it is given a new “layout manager,” of type FlowLayout. The layout manager is the way that the pane implicitly decides where to place the control on the form. The normal behavior of an applet is to use the BorderLayout, but that won’t work here because (as you will learn later in this chapter when controlling the layout of a form is examined in more detail) it defaults to covering each control entirely with every new one that is added. However, FlowLayout causes the controls to flow evenly onto the form, left to right and top to bottom.