Chapter 30: Exploring Swing 881
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Create an icon.
ImageIcon ii = new ImageIcon("france.gif");
// Create a label.
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
// Add the label to the content pane.
add(jl);
}
}
Output from the label example is shown here:
JTextField
JTextFieldis the simplest Swing text component. It is also probably its most widely used text
component.JTextFieldallows you to edit one line of text. It is derived fromJTextComponent,
which provides the basic functionality common to Swing text components.JTextFielduses
theDocumentinterface for its model.
Three ofJTextField’s constructors are shown here:
JTextField(intcols)
JTextField(Stringstr, intcols)
JTextField(Stringstr)
Here,stris the string to be initially presented, andcolsis the number of columns in the text
field. If no string is specified, the text field is initially empty. If the number of columns is not
specified, the text field is sized to fit the specified string.
JTextFieldgenerates events in response to user interaction. For example, anActionEvent
is fired when the user pressesENTER. ACaretEventis fired each time the caret (i.e., the
cursor) changes position. (CaretEventis packaged injavax.swing.event.) Other events are