Java: Summary - Basic GUI Components

Components share many common methods, for example:
cmp.requestFocus(); Puts focus (eg, blinking cursor) in field, select button, etc.
cmp.setFont(f); Sets font.
JLabel - For fixed text.
lbl = new JLabel(t) Creates JLabel with text t on it.
lbl = new JLabel(t, align) Align text JLabel.LEFT, JLabel.CENTER, or JLabel.RIGHT.
lbl = new JLabel(icon) Displays icon (eg, ImageIcon).
lbl = new JLabel(icon, align) Align icon to JLabel.LEFT, JLabel.CENTER, or JLabel.RIGHT.
JTextField - Box containing one line of text.
tf = new JTextField(n); Creates textfield n characters wide.
s = tf.getText(); Returns string in textfield.
tf.setText(s); Sets text to s.
tf.addActionListener(lst); Action listener lst will be called if enter typed.
tf.setEditable(bool); Don't allow user to edit text field used for output.
tf.setHorizontalAlignment(align); JTextField.LEFT (default), JTextField.CENTER, or JTextField.RIGHT
JButton - Standard clickable button.
btn = new JButton(t); Creates button with text t.
btn = new JButton(img); Creates button with icon img.
btn = new JButton(t, img); Creates button with both text and icon.
btn.addActionListener(actlstnr); Action listener actlstnr called when button clicked.
btn.setEnabled(bool); Used to enable/disable button.
JTextArea - Box containing multiple lines of text separated by '\n'.
ta = new JTextArea(rows, cols); Creates textarea with specifed number of rows and columns.
s = ta.getText(); Returns string in text area.
ta.setText(s); Sets text to s.
ta.append(s); Adds s to end of existing text.
ta.insert(s, pos); Inserts s at position pos.
ta.setEditable(bool); Don't allow user to edit textarea if used for output.
ta.setLineWrap(bool); Allow/disallow long lines to wrap.
ta.setWrapStyleWord(bool); Call setLineWrap(true) first. true wraps at word boundaries, false (default) at characters.
ta.setBorder(brdr); Add space between text and edge. Eg, to add 4 pixels use brdr BorderFactory.createEmptyBorder(4,4,4,4)
JCheckBox - Check box followed by text. Use either listener or check with isSelected().
cb = new JCheckBox(text); Creates check box initially unchecked.
cb = new JCheckBox(text, bool); Creates check box with checked state tf.
b = cb.isSelected(); Returns bool if box is checked/unchecked.
cb.setSelected(bool); Sets checked state to tf.
cb.addActionListener(actlstnr); Adds ActionListener, which is called whenever user clicks.
cb.setEnabled(bool); Used to enable/disable check box.

Copyleft 2007 Fred Swartz