Chapter 3 - GUI and Multimedia
Chapter 3 - GUI and Multimedia
minimize
maximize
close
0 Before Java 2 each top-level container had only one layer. Java 2
top-level containers (JFrame, JApplet, ...) have several layers
(panes): root, content, layered, and glass. Programs normally
reference only the content pane. There are two programming
idioms for using the content pane: (1) using the preassigned
pane (recommended), or (2) building your own pane.
0 Naming convention
0 It is common to name the content pane content or contentPane.
45
Jlabel(cont)
HTML in JLabels
0 You may put HTML text in a JLabel. In this case the text should
begin with <html> and end with </html>.
0 JLabel font and color
The most user-friendly interfaces are usually obtained by using the
default appearance (font, color, background), but there are cases
where you want to change these.
0 Appearance: setting the font
The font of a JLabel can be changed like this.
46
Jlabel(cont)
HTML in JLabels
0 Appearance: setting the text color
Use the setForeground method to set the text color.
JLabel title = new JLabel(“Name :", JLabel.CENTER);
title.setForeground(Color.white);
0 Appearance: setting the background color
Because a JLabel's background is transparent, there is no effect
from using the setBackground method. To make a new background,
you need to create a JPanel with the appropriate color and put the
label on that. For example
JLabel title = new JLabel(“Enter your name");
title.setForeground(Color.white);
JPanel titlePanel = new JPanel();
titlePanel.setBackground(Color.blue);
titlePanel.add(title);
// adds to center of panel's default BorderLayout. 47
Jlabel(cont)
JLabel for output
0 Why using JLabel for output is usually bad
It's possible to change the text of a JLabel, although this is not generally a
good idea after the user interface is already displayed. For output
JTextField is often a better choice. The use of JLabel for output is
mentioned because some textbooks display output this way. Here are
some reasons not to use it.
0 Can't copy to clipboard. The user can not copy text from a JLabel, but
can from a JTextField.
0 Can't set background. Changing the background of individual
components probably isn't a good idea, so this restriction on JLabels is
not serious. You can change the background of a JTextField, for better or
worse.
0 Text length. This is where there are some serious issues. You can
always see the entire text in a JTextField, altho you might have to scroll
it it's long. There are several possibilities with a JLabel. You may either
not see all of the long text in a JLabel, or putting long text into a JLabel
may cause the layout to be recomputed, resulting in a truly weird user
experience.
48
Jlabel(cont)
0 Changing the text of a JLabel
Most JLabels are never changed, except for internationalization, and
that is done before the user interface is shown. To change the text,
use
yourLabel.setText(String newText);
49
JTextField
0 javax.swing.JTextField has two uses.
Input. The user can enter one line of text (a String)
Output. To display one line of text.
0 If you need a component that displays or allows entry of
more than one line, use a JTextArea.
0 Overview of methods JTextField
JTextField(width)
setText(text)
String getText()
addActionListener(listener)
setEditable(true/false)
setFont(font)
setHorizontalAlignment(align)
Chap-3 Adv Prog requestFocus(align) 50
JTextField(cont)
To use a JTextField for Input
1. Declare a JTextField as an instance variable. Reason: If it's an
instance variable, it can be seen in all methods in the class.
2. Assign an initial value to this variable by calling the JTextField
constructor. Specify the approximate field width in the constructor.
Example:
JTextField yourInpuField = new JTextField(16);
3. Add the text field to a container.
content.add(yourInputField);
or to add it to a JPanel p
p.add(yourInputField);
4. Input is done by calling the getText().
1. Get the string in the text field by calling yourTextField.getText() method
whenever you need it. This is probably the most common way.
String x = yourInputField.getText();
2. Attach an action listener to the text field. It is called whenever the user
types Enter in that field. The listener can then get the text and process it.
Chap-3 Adv Prog 51
JTextField(cont)
To use a JTextField for Output
0 Using a JTextField for output is almost the same as for input, but . . .
1. Set the text field with yourTextField.setText(someString)
2. If it's only for output, call .setEditable(false) so the user can't
change the field.
0 Here is the sequence.
1. Declare and initialize a JTextField as a field variable (instance
variable). Example:
JTextField myOutput = new JTextField(16);
You can also set the initial value in the field
JTextField myOutput = new JTextField("someInitialValue", 20);
2. Add the text field to a container. For example, to add it to JPanel p.
p.add(myOutput);
3. Setting the value of the text field. Whenever you want put a string
value in the text field, call myOutput.setText("Some text").
myOutput.setText("some text"); 52
Chap-3 Adv Prog
JTextField(cont)
0 Constructors
JTextField tf = new JTextField(int columns);
The number of columns is approximate because the width of text
depends on the font and width of individual characters.
53
Chap-3 Adv Prog
JTextField(cont)
Common methods
0 Here are some of the most common methods use with text fields: Assume
these declarations
JTextField tf;
ActionListener listener;
String s,
text;
Font f;
//--- When used for input.
s = tf.getText(); // gets the text from the JTextField
tf.addActionListener(listener);// Optional listener intialization.
//--- When used for output.
tf.setText(text); // Sets text in the JTextField.
tf.setEditable(false); // Initialization to disallow user changes.
//--- To change the appearance.
tf.setHorizontalAlignment(align);//See below for possible values.
tf.setFont(f); // sets the font for the text 54
Chap-3 Adv Prog
JTextField(cont)
Appearance of a JTextField - font, alignment
0 yourField.setFont(Font f); sets the font for the text. Often numbers are
aligned to the right (eg, in the display of a calculator), and text is aligned to the
left.
0 yourField.setHorizontalAlignment(align); sets the alignment of
the text in the field, where align is one of these values: JTextField.LEFT
(the default), JTextField.CENTER, or JTextField.RIGHT.
0 Example
JTextField userID; // declare a field . . .
userID = new JTextField(8); // create field approx 8 columns wide. p.add(userID);
// add it to a JPanel
userID.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
... // THIS CODE IS EXECUTED WHEN RETURN IS TYPED
}
}
55
); Chap-3 Adv Prog
JTextField(cont)
Use JPasswordField for passwords
0 Use a JPasswordField component for a field where the characters
the person enters are replaced by some other character.
JPasswordField is a subclass of JTextField.
Focus
0 To select a JTextField so that user typing occurs in that field, you
must give the JTextField focus. For example, the nameField
JTextField can be given focus with:
nameField.requestFocus(); Chap-3 Adv Prog
56
JTextArea
0 A javax.swing.JTextArea is a multi-line text component to display
text or allow the user to enter text.
0 Using a JTextArea for output -- Setting the text
0 Assume: JTextArea ta;
int i, w, pos, start, end, line;
String s; boolean b;
Font f;
Reader reader;
Writer writer;
Result Method Description
Constructors
ta = new JTextArea(rows, cols); Creates text area. cols is approx char
width.
ta = new JTextArea(s, rows, cols); As above, but also containing initial
Chap-3 Adv Prog 57
string s.
JTextArea(cont)
Result Method Description
Setting text
ta.setText(s); Replaces all text with s.
ta.append(s); Appends s to the end.
ta.insert(s, pos); Inserts s at position pos.
ta.replaceRange(s, start, end); Replace start to end with s.
Getting text
s = ta.getText(); Returns all text. Use methods below to get
individual lines.
i = ta.getLineCount(); Returns number of lines in the text area.
i = ta.getLineStartOffset(line); Returns character index of beginning of line
line. May throw
javax.swing.text.BadLocationException.
i = ta.getLineEndOffset(line); Returns character index of end of line line.
May throw
javax.swing.text.BadLocationException.
Chap-3 Adv Prog 58
JTextArea(cont)
Result Method Description
Changing the appearance/function
ta.setBorder(brdr); Text is tight against edge. See example below
to add space.
ta.setLineWrap(b); Lines wrapped if true. Default false.
ta.setWrapStyleWord(b); If wrapping on (see above), wraps at words
(true) or chars (false). Default false.
ta.setTabSize(w); Number of max width chars in a tab.
ta.setFont(f); Displays using Font f.
ta.setEditable(b); Set false to disable user editing.
ta.setCaretPosition(i); Set caret position. If content is scrolled,
setCaretPosition(0) will move to top.
Reading and writing to/from a JTextArea
ta.read(reader, null); Reads text from reader into text area. May
throw IOException.
ta.write(writer); Writes text from text area to writer. May
Chap-3throw
Adv ProgIOException. 59
JTextArea(cont)
Scrolling
0 JTextArea doesn't support scrolling itself but you can easily add
the JTextArea to a JScrollPane. JScrollPane creates scrollbars as
needed. For example,
Components Description
JButton This is a standard button which can have text,
icon, or both.
Listener: addActionListener(...)
JCheckBox The box next to the text can be toggled on or off.
JRadioButton, ButtonGroup Radio buttons are a group of buttons that can have
at most one button toggled on. When you click one
button, that button is toggled on, and all others
are set to off.
JMenuItem Menu items are a kind of button.
JToggleButton Changes between two states: on and off. Stays
on/off until the next click.
69
Jbutton(cont)
Buttons with Icons
Methods to change the icon on a JButton
0 It is common to show different icons when the button is disabled, the
mouse is over it (rollover), etc. Java recognizes seven (7) different
states for a button, and you can set a different image for each state.
0 Java computes two button images automatically: the disabled image is
computed from the normal image, and the selected, disabled image is
computed from the selected image if one is supplied.
0 Rollover image changes are not automatic -- first you must call
b.setRolloverEnabled(true);.
JButton b = new JButton(Icon x); // Create button with normal icon
b.setIcon(Icon x);
b.setDisabledIcon(Icon x);
b.setPressedIcon(Icon x);
b.setSelectedIcon(Icon x);
b.setDisabledSelectedIcon(Icon x);
b.setRolloverEnabled(boolean b); // turn on before rollovers work
b.setRolloverIcon(Icon x);
70
b.setRolloverSelectedIcon(Icon x);
JComboBox (uneditable)
Making Choices
0 There are several ways to select one of many fixed choices: radio
buttons, a menu, a list, or a (uneditable) combo box. A combo box
(JComboBox) is a popup menu and is often the best component to use
because it uses less space than radio buttons or a list, and it shows as
part of a "form" so the user realizes it's there, unlike a menu.
You can also use an editable combo box, and in this case the user can
either choose from the pop-up menu or type in a value.
Constructor
0 An easy way to build a combo box is to initialize an array (or Vector,
but not yet the new Collections types) of strings and pass it to the
constructor. Objects other than strings can be used, but this is the
most common. The list also be built by successive calls to the add
method.
String[] dias = {"lunes", "martes", "miercoles"};
JComboBox dayChoice = new JComboBox(dias);
71
Chap-3 Adv Prog
JComboBox (uneditable)
Common methods
0 In these prototypes, assume the following. int index;
String item;
String obj; // obj can be any object type, but is commonly
String JComboBox cb = new JComboBox(. . .);
Result Call Description
cb.addActionListener(...); Add listener -- same as for button.
Modifying a JComboBox
cb.setSelectedIndex(index); Set default, visible, choice.
cb.setSelectedItem(obj); Set default, visible, choice.
cb.add(item); Add additional item to the list
cb.insert(item, index); Add additional item after index.
cb.remove(item); Remove item from the list
cb.remove(index); Remove item as position index
Testing a JComboBox
index = cb.getSelectedIndex(); Return index of selected item.
72
obj = cb.getSelectedItem(); Chap-3Return
Adv Progselected item.
JComboBox (uneditable)
Events
0 A JComboBox generates both ActionEvents (like buttons, text fields, etc), or
ItemEvents. Because it is easier to work with ActionEvents, we'll ignore the
ItemEvents. When the user chooses an item from a combo box, an ActionEvent is
generated, and the listener's actionPerformed method is called. Use either
getSelectedIndex to get the integer index of the item that was selected, or
getSelectedItem to get the value (eg, a String) that was selected.
0 Example
0 This example creates a JComboBox, and adds a listener to it. The getSelectedItem
method returns an Object type, so it's necessary to downcast it back to a
77
Radio Buttons(cont)
0 Radio buttons (javax.swing.JRadioButton) are used in groups
(java.awt.ButtonGroup) where at most one can be selected. The
example below produced this image. A radio button group starts
with all buttons deselected, but after one is selected the only way
to have them appear all off is to have an invisible button that is
selected by the program.
Advanced Appearance
0 In addition to tick marks, you can specify text or icon labels at
any values that you specify using setLabelTable(...). You can
also specify which end of the slider should have the high or low
values using setInverted(true/false).
frame.setJMenuBar(mbar);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
92
Dialogs
0 There are several ways to build dialog boxes:
0 JOptionPane - Simple Dialogs This is a very easy way (one
statement) to build simple dialogs. Usually this, JFileChooser,
and maybe JColorChooser are the only dialog classes that you
need.
0 JFileChooser This will create and control a standard file
chooser dialog.
javax.swing.JColorChooser You can call one static method
(Color.showDialog(. . .)) to display a dialog that lets the user choose
a color, or you can add listeners to make a more complicated dialog
interaction, or you can use this class to create a color chooser pane.
javax.swing.Jdialog This can be used for building dialogs that are
too complicated for JOptionPane.
Chap-3 Adv Prog 93
Dialogs(cont)
Dialogs are attached to window (frame)
0 Every dialog is attached to a window (frame). When the window
in iconified, the dialog will automatically disappear, and it will
automatically reappear when the window is deiconified. When
the window is destroyed, the dialog will disappear.
import javax.swing.JOptionPane;
public class JOptionPaneTest1 {
public static void main(String[] args) {
String ans;
ans = JOptionPane.showInputDialog(null, "Speed in miles/ hour?");
double mph = Double.parseDouble(ans);
double kph = 1.621 * mph;
JOptionPane.showMessageDialog(null, "KPH = " + kph);
System.exit(0);
}
}
97
JOptionPane(eg 1)
This line displays a String, an input text field
(JTextField), and OK and CANCEL buttons. If the user
presses the OK button, the string in the text field is
returned. If the user didn't type anything, the string
"" is returned. If the user presses the CANCEL button,
null is returned. Because this call returns a String, it's
necessary in the next line to convert it into a double
to do the arithmetic calculation.
98
JOptionPane(eg 2)
0 This program produces the dialog boxes below.
import javax.swing.JOptionPane;
public class JOptionPaneTest1 {
public static void main(String[] args) {
String[] choices = {"Democratic", "Republican", "None of your business", "Quit"};
int response = JOptionPane.showOptionDialog(
null // Center in window.
, "How did you vote?" // Message
, "Party Poll" // Title in titlebar
, JOptionPane.YES_NO_OPTION // Option type
, JOptionPane.PLAIN_MESSAGE // messageType
, null // Icon (none)
, choices // Button text as above.
, "None of your business" // Default button's label
);
System.exit(0);
}
99
}
JDialog (cont)
Example
JFrame frame = new JFrame();
Object[] options = {"Yes!", "No!", "Cancel"};
int n = JOptionPane.showOptionDialog(
frame,
"Here goes the description",
"This is the title ",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options, //the titles of buttons
options[2] //default button title
);
question
information
warning
error
103
JFileChooser(cont)
Getting the selected file or directory
0 After checking for JFileChooser.APPROVE_OPTION, the File
value of the selection is returned from a call on getSelectedFile.
104
JFileChooser(cont)
Files, directories, or both
0 By default a file chooser allows the user to select only files. To allow
selection of either files or directories, or only directories, use one of
the following calls.
fc.setFileSelectionMode(JFileChooser.FILES_ONLY); // default
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
JFileChooser(cont)
Filtering files
0 You can specify the kinds of files that should be shown (eg, with a specific
extension, ...), by supplying a JFileFilter.
myChooser.setFileFilter(FileFilter filter);
Eg to select only picture files
JFileChooser myChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt and
.java files", "txt", "java");
myChooser.setFileFilter(filter);
JFileChooser(cont)
Filtering files(cont)
Eg to select only picture files
JFileChooser myChooser = new JFileChooser();
String[] okFileExt = {"jpg", "png", "gif"};
@Override
public boolean accept(File file) {
for(String extension : okFileExt){
if(file.getName().toLowerCase().endsWith(extension)){
return true;
}
return false;
}
return false;
}
};
JFileChooser(cont)
Specify a start directory in the constructor
0 The file chooser will start the file dialog at some default directory, for
example, "C:\My Documents". To start the dialog at a different directory
(called the current directory), specify the directory path as a String or File
value in the JFileChooser constructor.
JFileChooser m_fileChooser = new JFileChooser("C:\home");
The current directory is ".".
0 Portability warning: If you put system specific file paths in your code, the
program will not be portable to other systems. Note that the above call is
therefore not portable.
JTabbedPane
0 Description.
The JTabbedPane container allows many panels to occupy the same area of the
interface, and the user may select which to show by clicking on a tab. A tab may
also be selected by the program.
0 Constructor
JTabbedPane tp = new JTabbedPane(); // Defaults to tabs along the top edge.
JTabbedPane tp = new JTabbedPane(edge);
Where edge specifies which edge the tabs are on
JTabbedPane.TOP (default)
JTabbedPane.RIGHT
JTabbedPane.BOTTOM
JTabbedPane.LEFT
JTabbedPane (cont)
Adding tabs to the JTabbedPane
0 Add tabs to a tabbed pane by calling addTab and passing it a String title and a
component (eg a JPanel) to display in that tab. For example,
JTabbedPane display = new JTabbedPane();
display.addTab("Diagram View", diagramPanel);
display.addTab("SQL View" , sqlPanel);
display.addTab("Instructions", instructionPanel);
JFrame JFrame
JPanel
containers
JPanel
JButton
JButton JLabel
JLabel
0 Create:
0 Frame
JLabel JButton
0 Panel
0 Components
0 Listeners
0 Add: (bottom up) JPanel
0 listeners into components
0 components into panel
0 panel into frame
JFrame
Chap-3 Adv Prog 114
What Is Layout?
0 A layout is a set of rules that defines how graphical components
should be positioned in a container.
0 Layouts tell Java where to put components in containers
(JPanel, content pane, etc). Every panel (and other container)
has a default layout, but it's better to set the layout explicitly for
clarity.
0 Create a new layout object (using one of its constructors) and
use the container's setLayout method to set the layout. Each
layout has its own way to resize components to fit the layout,
and you must become familiar with these.
115
What Is Layout?(cont)
0 There two ways to position a component is a container:
1. Using a predefined layout and allowing the layout to decide
where to position the component. This is a soft way of
positioning a component. If the container changes its size, the
component's position will be adjusted. But you may not able
to get precisely where you want to component to be.
2. Specifying the position of the component using the
container's coordinates. This is a hard way of positioning a
component. You can get precisely where you want the
component to be. But if the container changes its size, the
component's position will not be adjusted.
Where hgap and vgap are the distances in pixels between the
regions.
120
Chap-3 Adv Prog
BorderLayout(cont)
public static void main(String[] a) {
JFrame myFrame = new JFrame("FlowLayout Test");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container myPane = myFrame.getContentPane();
myPane.setLayout(new BorderLayout());
myPane.add(new JButton("North"), BorderLayout.NORTH);
myPane.add(new JButton("South"), BorderLayout.SOUTH);
myPane.add(new JButton("East"), BorderLayout.EAST);
myPane.add(new JButton("West"), BorderLayout.WEST);
myPane.add(new JButton(new ImageIcon("java.gif")),
BorderLayout.CENTER);
myFrame.pack();
myFrame.setVisible(true);
}
0 The window to the left is the default size after packing the FlowLayout. The window
on the right shows the same window after it has been resized by dragging the lower-
right corner, resulting in components flowing down onto other lines.
Cont….
Chap-3 Adv Prog 126
FlowLayout(cont)
private static JPanel getFieldPanel() {
JPanel p = new JPanel(new FlowLayout());
p.setBorder(BorderFactory.createTitledBorder("Details"));
p.add(new JLabel("Name:"));
p.add(new JTextField(16));
p.add(new JLabel("System:"));
p.add(getSystemPanel()); //calling the panel which has the radiobuttons
p.add(new JLabel("Language:"));
p.add(getLanguagePanel()); //calling the panel which has the checkboxes
p.add(new JLabel("Year:"));
p.add(new JComboBox(new String[] {"2001","2002","2003"}));
return p;
}
Cont….
Chap-3 Adv Prog 127
FlowLayout(cont)
private static JPanel getButtonPanel() {
JPanel p = new JPanel(new FlowLayout());
p.add(new JButton("OK"));
p.add(new JButton("Cancel"));
return p;
}
private static JPanel getLanguagePanel() {
JPanel p = new JPanel(new FlowLayout());
p.add(new JCheckBox("Java",true));
p.add(new JCheckBox("C++",true));
p.add(new JCheckBox("Perl",false));
return p;
}
Cont….
This creates a rigid area component 10 pixels wide and 0 pixels high and adds
it to a panel.
0 Glue is an invisible component that can expand. It's more like a spring or
sponge than glue. Put a glue component where extra space should appear
(disappear from) when a window is resized. Use vertical glue in a vertical
BoxLayout and horizontal glue in a horizontal layout. For example, this will
allow extra vertical space between two buttons.
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(button1);
p.add(Box.createVerticalGlue()); // This will expand/contract as needed.
p.add(button2);
0 Use Box.createHorizontalGlue() for horizontal expansion.
137
Chap-3 Adv Prog
BoxLayout(cont)
BoxLayout spacing(cont)
Struts
p.add(Box.createVerticalStrut(n)); // n pixels of vertical space.
p.add(Box.createHorizontalStrut(n)); // n pixels of horizontal space.
Create a strut by specifying its size in pixels, and adding it to the panel at the
point you want the space between other components.
Empty Cells
0 There is no way to leave a cell empty in a grid layout. Although it
often works ok to leave the final cells empty, there are reports of
problems, so you should fill out the last cells in the final row too.
The easiest way to do this is to put an empty label in any cell you
want to skip.
Eg. p.add(new JLabel(""));
151
GridLayout(cont)
import java.awt.*; Let’s do our exercise
- Details ----------- --------------
import javax.swing.*; | Name: Text |
| System: Radio button |
public class GridLayoutTest { | Language: Check box
| Year: Dropdown |
|
155
GridBagLayout
0 GridBagLayout – is one of the most flexible and complex layout managers
the Java platform provides. And it :
0 Divides the container into rows and columns. The number of rows
and the number of columns are unlimited. Rows and columns are not
equally divided.
0 Places components into the specified cells.
0 Uses the default size of each component.
0 Keeps component sizes unchanged when the container is resized.
0 Provides individual layout constraints for each component to control
its layout behavior.
0 GridBagLayout lays out components based on a grid with rows and
columns that need not all be the same size. If you're familiar with HTML
tables, you'll feel comfortable with the idea. Unfortunately,
GridBagLayout is awkward and error-prone to use.
156
GridBagLayout(cont)
Abandon hope, all who use GridBagLayout
0 Although GridBagLayout can produce acceptable results, it's not a happy
story.
0 It is very difficult to work with because eleven constraint values are
used for each component! These constraint values are bundled in a
java.awt.GridBagConstraints object. Fortunately, most of them have
reasonable defaults.
0 The layout doesn't have features which specifically help to use Sun's (or
anyone else's) Human Interface Guidelines, for example in handling gaps.
0 Spacing is specified in pixels, which provides no flexibility for screen
resolution and font changes.
0 Quote from Otaku, Cedric's blog: "GridBagLayout is an absolute disaster
and the perfect example of something that is completely flawed and
violates with a stunning regularity the principle of least surprise."
0 Some prefer to call it "GridBugLayout".
157
GridBagLayout(cont)
0 Subpanels for unrelated components. An entire window may
require use of nested panels -- don't try to force everything into one
giant GridBagLayout. If some groups of components (eg, radio
buttons, groups of buttons, checkboxes) are unrelated to alignment
with other components, put them in their own panel and use an
appropriate layout (often GridLayout).
Unequal rows and columns
0 The underlying idea is rows and columns, similar to HTML tables.
0 Rows and columns don't all have to be same size. The size of each
row and column is adjusted depending on maximum component size
in the row/column and their constraints.
0 A component display area may span several rows and/or columns.
Describe this area by giving the row, column, width (in columns), and
height (in rows).
0 A components doesn't have to fill its display area; constraints
describe how to align it within its area.
158
GridBagLayout(cont)
Three categories of constraint parameters
0 GridBagLayout performs three functions using values from the
GridBagConstraints parameter in the add() method. The names are the
following.
1. Grid position, width and height describe the display area.. gridx, gridy,
gridwidth, and gridheight.
2. Position within the display area. fill, anchor, insets, ipadx, and ipady.
3. Identifying rows and columns which receive extra space on expansion.
weightx, and weighty.
Constructor
JPanel p = new JPanel(new GridBagLayout()); or
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
Do not give the number of rows and columns when you create a new
GridBagLayout. They are computed by the layout manager as a consequence of
what you add. 159
GridBagLayout(cont)
Adding a component
0 Components are added to JPanel p like this:
p.add(component, constraintObj);
160
GridBagLayout(cont)
GridBagConstraints fields
0 The fields can divided into three groups:
1. Necessary - row and column coordinates, width and height in terms of
rows and columns. Describe the location and size (in rows and columns)
of the component using gridx, gridy, gridwidth, and gridheight.
2. Common - expandability and alignment. If a column or row can use extra
space when a window is expanded, set weightx and weighty to 1.0; you
will rarely want to use other values.
Use fill depending on what the type of component is. For example, a JTextField can
usually grow horizontally, so you would use
gbc.fill = GridBagConstraints.HORIZONTAL; to allow it to stretch.
Use anchor to tell which edges of the display area a component should be attached
to.
3. Less common - surrounding spacing. You can also control the space
around a component with ipadx and ipady. To control the amount of
unused space around a component, use insets.
161
GridBagLayout(cont)
GridBagConstraints
0 gridx, gridy : Specify the row and column at the upper left of the
component. The leftmost column has address gridx=0 and the top row has
address gridy=0. Use GridBagConstraints.RELATIVE (the default value) to
specify that the component be placed just to the right of (for gridx) or just
below (for gridy) the component that was added to the container just before
this component was added. We recommend specifying the gridx and gridy
values for each component rather than just using
GridBagConstraints.RELATIVE; this tends to result in more predictable
layouts.
0 fill : Used when the component's display area is larger than the component's
requested size to determine whether and how to resize the component.
Valid values (defined as GridBagConstraints constants) include NONE (the
default), HORIZONTAL (make the component wide enough to fill its display
area horizontally, but do not change its height), VERTICAL (make the
component tall enough to fill its display area vertically, but do not change its
width), and BOTH (make the component fill its display area entirely).
162
GridBagLayout(cont)
GridBagConstraints(cont)
0 ipadx, ipady Specifies the internal padding: how much to add to the size of
the component. The default value is zero. The width of the component will
be at least its minimum width plus ipadx*2 pixels, since the padding applies
to both sides of the component. Similarly, the height of the component will
be at least its minimum height plus ipady*2 pixels.
164
GridBagLayout(cont)
GridBagConstraints(cont)
0 anchor Used when the component is smaller than its display area to
determine where (within the area) to place the component. Valid values
(defined as GridBagConstraints constants) are CENTER (the default),
PAGE_START, PAGE_END, LINE_START, LINE_END, FIRST_LINE_START,
FIRST_LINE_END, LAST_LINE_END, and LAST_LINE_START. Here is a picture
of how these values are interpreted in a container that has the default, left-
to-right component orientation.
FIRST_LINE_START PAGE_START FIRST_LINE_END
Version note: The PAGE_* and *LINE_* constants were introduced in 1.4.
Previous releases require values named after points of the compass. For
example, NORTHEAST indicates the top-right part of the display area. We
recommend that you use the new constants, instead, since they enable
165
easier localization.
GridBagLayout(cont)
GridBagConstraints(cont)
0 weightx, weighty : Specifying weights is an art that can have a significant
impact on the appearance of the components a GridBagLayout controls.
Weights are used to determine how to distribute space among columns
(weightx) and among rows (weighty); this is important for specifying
resizing behavior.
Unless you specify at least one non-zero value for weightx or weighty, all the
components clump together in the center of their container. This is because
when the weight is 0.0 (the default), the GridBagLayout puts any extra space
between its grid of cells and the edges of the container.
Generally weights are specified with 0.0 and 1.0 as the extremes: the
numbers in between are used as necessary. Larger numbers indicate that the
component's row or column should get more space. For each column, the
weight is related to the highest weightx specified for a component within
that column, with each multicolumn component's weight being split
somehow between the columns the component is in. Similarly, each row's
weight is related to the highest weighty specified for a component within
that row. Extra space tends to go toward the rightmost column and bottom 166
row.
GridBagLayout(cont)
gridx The int column (gridx) and row (gridy) of the component. If requires more
gridy than one cell (gridwidth or gridheight > 1), this is the coordinate of the top-
left cell. The row and columns start at zero. The value
GridBagConstraints.RELATIVE places the component in the next position.
gridwidth Number of columns or rows the component occupies.
gridheight GridBagConstraints.REMAINDER indicates that this component should fill
out all rows or columns to the end. Default 1.
weightx These double variables (default value 0) are used in calculating where
weighty space is allocated in rows and columns when a window is resized. extra
space should be allocated in a column horizontally (weightx) and row
vertically (weighty). A column width is originally calculated as the
maximum width of the preferred sizes of the components in that column. If
a component is narrower than the column width, the value of the fill
attribute is used in deciding how to use that extra space (see below).
Extra horizontal space is allocated to a column in proportion to the
maximum weightx value for that column. If weightx is zero, no extra space
is allocated. Because these weights are relative, you can assign any
arbitrary positive double value to produce the desired layout, although it is
common to work in the range 0-1. The analogous procedure is performed
for the row heights using weighty. 167
GridBagLayout(cont)
fill Fill specifies how the component should expand within its display area if
the area width/height is larger than its preferred size.
GridBagConstraints.NONE // Can't expand (Default)
GridBagConstraints.VERTICAL // Expand vertically
GridBagConstraints.HORIZONTAL // Expand horizontally
GridBagConstraints.BOTH // Expand vertically and horizontallyFor
example, a text field typically expands horizontally
(GridBagConstraints.HORIZONTAL), a text area expands vertically and
horizontally (GridBagConstraints.BOTH), and a button might not expand
at all (GridBagConstraints.NONE). If a component isn't expanded to fill the
space, the anchor attribute (see below) is used to specify where it goes
within that cell. Default value GridBagConstraints.NONE.
anchor If the component doesn't occupy its entire display area, anchor specifies
where it should be placed. The location is usually given as a compass
direction. (A relative system which works for both right-to-left and left-to-
right languages is also available). GridBagConstraints.CENTER (the
default), GridBagConstraints.NORTH GridBagConstraints.SOUTH
GridBagConstraints.NORTHEAST GridBagConstraints.SOUTHWEST
GridBagConstraints.EAST GridBagConstraints.WEST
GridBagConstraints.SOUTHEAST GridBagConstraints.NORTHWEST 168
GridBagLayout(cont)
insets A java.awt.Insets object adds padding space to the component. Insets
should be rarely used because they often produce bad results, with the
exception of JPanels and JLabels. The constructor parameters (in pixels)
specify the top, left, bottom, right. For example, gbc.insets = new
Insets(10, 5, 10, 4); Default value: Insets(0,0,0,0).
ipadx These int fields specify an increase or decrease in the horizontal and/or
ipady vertical preferred size of the component. Default value 0. Negative values
can be used to tighten the spacing. These values are rarely useful,
although they can be used for fine-tuning spacing.
169
Java Idiom GridBagLayout(cont)
0 It's common to write a utility method which sets the fields of a GridBagConstraints
object.
For example,
GridBagConstraints gbc = new GridBagConstraints();
...
private void set_gbc(int row, int column, int width, int height, int fill) {
gbc.gridy = row;
gbc.gridx = column;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.fill = fill; // GridBagConstraints.NONE .HORIZONTAL .VERTICAL .BOTH
// leave other fields (eg, anchor) unchanged.
}
...
set_gbc(3, 2, 2, 1, GridBagConstraints.HORIZONTAL);
gbc.insets = new Insets(3,3,3,3); // put spacing around this field.
p.add(myTextField, gbc);
170
GridBagLayout(cont)
Adding a component
0 To add myField to the third row (2) and first column (0),
where the button will be one grid cell wide and one high, and
it will be able to expand horizontally, do this:
set_gbc(2, 0, 1, 1, GridBagConstraints.HORIZONTAL);
gridbag.setConstraints(myField, gbc);
panel.add(myField);
Opinion
0 GridBagLayout is not a nice piece of software. The
GridBagConstraints object is awkward to use. It allows you to
make careless mistakes in the layout without warnings or
error messages.
171
GridBagLayout(cont)
import javax.swing.*;
public class DemoGridBag {
public static void main(String[] a){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
JPanel pane = new JPanel();
pane.setLayout(new GridBagLayout());
JButton button;
GridBagConstraints c = new GridBagConstraints();
Cont…
GridBagLayout(cont)
private static JPanel getFieldPanel() {
JPanel p = new JPanel(new GridBagLayout());
p.setBorder(BorderFactory.createTitledBorder("Details"));
GridBagConstraints c = new GridBagConstraints();
setMyConstraints(c,0,0,GridBagConstraints.EAST); p.add(new JLabel("Name:"),c);
setMyConstraints(c,1,0,GridBagConstraints.WEST); p.add(new JTextField(16),c);
setMyConstraints(c,0,1,GridBagConstraints.EAST);p.add(new JLabel("System:"),c);
setMyConstraints(c,1,1,GridBagConstraints.WEST); p.add(getSystemPanel(),c);
setMyConstraints(c,0,2,GridBagConstraints.EAST);
p.add(new JLabel("Language:"),c);
setMyConstraints(c,1,2,GridBagConstraints.WEST); p.add(getLanguagePanel(),c);
setMyConstraints(c,0,3,GridBagConstraints.EAST); p.add(new JLabel("Year:"),c);
setMyConstraints(c,1,3,GridBagConstraints.WEST);
p.add(new JComboBox(new String[] {"2001","2002","2003"}),c);
return p;
} 175
Cont…
GridBagLayout(cont)
private static JPanel getButtonPanel() {
JPanel p = new JPanel(new GridBagLayout());
p.add(new JButton("OK"));
p.add(new JButton("Cancel"));
return p;
}
private static JPanel getSystemPanel() {
JRadioButton unixButton = new JRadioButton("Unix",true);
JRadioButton winButton = new JRadioButton("Window",false);
ButtonGroup systemGroup = new ButtonGroup();
systemGroup.add(unixButton);
systemGroup.add(winButton);
JPanel p = new JPanel(new GridBagLayout());
p.add(unixButton);
p.add(winButton);
return p;
} 176
Cont…
GridBagLayout(cont)
private static JPanel getLanguagePanel() {
JPanel p = new JPanel(new GridBagLayout());
p.add(new JCheckBox("Java",true));
p.add(new JCheckBox("C++",true));
p.add(new JCheckBox("Perl",false));
return p;
}
private static void setMyConstraints(GridBagConstraints c, int gridx, int gridy, int anchor) {
c.gridx = gridx;
c.gridy = gridy;
c.anchor = anchor;
}
}//end of the class
0 All components are aligned correctly in
both directions now. And all components
are properly sized.
0 GridBagLayout seems to be good enough
for our example.
177
Layout(cont)
General advice
0 Initial Iterations. To quickly get the first iterations of a program
running, use FlowLayout. The result is often ugly, but if there are only a
few components, it's quick. FlowLayout is rarely the correct layout to use
in a finished program.
0 Simple programs. BorderLayout is often a good layout for simple
programs. More complicated layouts can often be nesting BorderLayouts
within other BorderLayouts. This and FlowLayout are the most
important layouts for beginners.
0 Grids of equal sized elements (eg, a calculator keypad), can be created
with GridLayout.
0 Single Rows or columns of components are sometimes best done with
BoxLayout.
0 More complicated layouts may require GridBagLayout. Getting a
GridBagLayout to work correctly can be time-consuming, but it produces
excellent results.
178
Null Layout
0 You can set the layout manager to null(cont.setLayout(null);), but this is generally
bad practice.
0 Eg
import javax.swing.*;
import java.awt.*;
public class NullLayoutTest {
public static void main(String[] a){
JFrame f = new JFrame();
f.setTitle("Null layout demo");
f.setSize(500,100);
f.setVisible(true);
}
180
}
Null Layout (cont)
Problems with null layout that regular layouts don't have
0 Difficult to change, therefore hard (expensive) to maintain
Moving, adding, removing, etc require a lot of recalculation. Relatively little work is required with
regular layouts.
0 Hard to get right in the first place
Exactly how do you get these coordinates?
0 System dependent
The components have different sizes in different systems. I once wrote a Java program that I
proudly showed to an important colleague, who unfortunately was using a different system. The
layout looked really, really bad - gaps, overlaps. What happened? Null layout! It was one of my
early programs and the last null layout I ever wrote.
0 Java version dependent
A little know fact is that between Java versions the rendering of components something changes
slightly. It's not big, but if you have things carefully aligned in null layouts, they may not be in the
next version of Java.
0 User setting dependent
Another little used feature is that the user can actually change Java's default settings for fonts etc. I
once decided I wanted larger fonts on the high resolution screen I had. Of course, this completely
breaks any null layouts altho regular layouts will adjust properly.
0 Not resizeable
It's not uncommon to have text fields/areas that the use might want to make larger by dragging
the lower right corner of the window. Impossible with null layouts, automatic with regular 181
layouts.
Reading on Layout
0 Read the following layout types:
CardLayout
GroupLayout
SpringLayout
182
Events -- Introduction
0 Events come from User Controls
When you define a user interface, you will usually have some way to
get user input. For example, buttons, menus, sliders, mouse clicks, ...
all generate events when the user does something with them.
User interface event objects are passed from an event source, such as
a button or mouse click, to an event listener, a user method which will
process them.
0 Every Input Control (JButton, JSlider, ...) Needs an Event Listener
If you want a control to do something when the user alters the
control, you must have a listener.
0 import Statements: To use events, you must import :-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
Types of Events
There are several kinds of events. The most common are:
User Control addXXXListener method in listener
JButton
JTextField addActionListener() actionPerformed(ActionEvent e)
JMenuItem
JSlider addChangeListener() stateChanged(ChangeEvent e)
JCheckBox addItemListener() itemstateChanged()
keyPressed(), keyReleased(),
key on component addKeyListener()
keyTyped()
mouseClicked(),
mouseEntered(),
mouse on component addMouseListener() mouseExited(),
mousePressed(),
mouseReleased()
mouseMoved(),
mouse on component addMouseMotionListener()
mouseDragged()
windowClosing(WindowEvent e),
JFrame addWindowListener()
...
Listener API Table
Listener Interface Adapter Class Listener Methods
ActionListener None actionPerformed(ActionEvent)
ancestorAdded(AncestorEvent)
AncestorListener None ancestorMoved(AncestorEvent)
ancestorRemoved(AncestorEvent)
CaretListener None caretUpdate(CaretEvent)
editingStopped(ChangeEvent)
CellEditorListener None
editingCanceled(ChangeEvent)
ChangeListener none stateChanged(ChangeEvent)
componentHidden(ComponentEvent)
componentMoved(ComponentEvent)
ComponentListener ComponentAdapter
componentResized(ComponentEvent)
componentShown(ComponentEvent)
componentAdded(ContainerEvent)
ContainerListener ContainerAdapter
componentRemoved(ContainerEvent)
Listener API Table
Listener Interface Adapter Class Listener Methods
changedUpdate(DocumentEvent)
DocumentListener none insertUpdate(DocumentEvent)
removeUpdate(DocumentEvent)
ExceptionListener none exceptionThrown(Exception)
focusGained(FocusEvent)
FocusListener FocusAdapter
focusLost(FocusEvent)
HierarchyBoundsList ancestorMoved(HierarchyEvent)
HierarchyBoundsAdapter
ener ancestorResized(HierarchyEvent)
HierarchyListener none hierarchyChanged(HierarchyEvent)
caretPositionChanged(InputMethod
Event)
InputMethodListener none
inputMethodTextChanged(InputMet
hodEvent)
Listener API Table
Listener Interface Adapter Class Listener Methods
internalFrameActivated(InternalFrameEvent)
internalFrameClosed(InternalFrameEvent)
internalFrameClosing(InternalFrameEvent)
InternalFrameListener InternalFrameAdapter internalFrameDeactivated(InternalFrameEvent)
internalFrameDeiconified(InternalFrameEvent)
internalFrameIconified(InternalFrameEvent)
internalFrameOpened(InternalFrameEvent)
ItemListener none itemStateChanged(ItemEvent)
keyPressed(KeyEvent)
KeyListener KeyAdapter keyReleased(KeyEvent)
keyTyped(KeyEvent)
contentsChanged(ListDataEvent)
ListDataListener none intervalAdded(ListDataEvent)
intervalRemoved(ListDataEvent)
f.add(b);
f.pack();
f.setVisible(true);
}
public class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, “You clicked ");
}
}
}
Anonymous Listeners
A common idiom
0 There is no need to define a named class simply to add a listener object to a
button. Java has a somewhat obscure syntax for creating an anonymous innner
class listener that implements an interface. For example,
class myPanel extends JPanel {
...
public MyPanel() {
...
//in the constructor JButton b1 = new JButton("Hello");
b1.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something for button b1
}
} );
……
……
Anonymous Listeners
Eg:
public class AnnoDemo {
public static void main(String[] a){
JButton but = new JButton("Press Me");
but.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
JOptionPane.showMessageDialog(null, "You pressed me");
System.out.println(“Button's clicked dude!");
}
});
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); When clicked :-
f.getContentPane().add(but);
f.pack();
f.setVisible(true);
} Consol Output
}
Button’s clicked
Eg: Anonymous Listeners
static JTextField tf = new JTextField(12);
static int count = 0;
public static void main(String[] args) {
JButton but = new JButton("Press Me");
but.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
count++;
tf.setText("clicked " + count);
}
});
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
p.add(but); p.add(tf);
f.add(p);
f.pack();
f.setVisible(true);
} //end of main
Top-level Listeners
Using this as a listener
Cont…
Top-level Listeners(cont)
public void actionPerformed(ActionEvent a){
String whichButton = a.getActionCommand();
JOptionPane.showMessageDialog(null, "You clicked! & the button is :" + whichButton);
}
public static void main(String[] a){
NewClass n = new NewClass();
}
}//end of class
Top-level Listeners(cont)
public class NewClass extends JFrame implements ActionListener {
JButton but1 = new JButton("click here 1");
JButton but2 = new JButton("click here 2");
//constructor
public NewClass(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
but1.addActionListener(this);
p.add(but1);
but2.addActionListener(this);
p.add(but2);
add(p);
pack();
setVisible(true);
}
Cont…
Top-level Listeners(cont)
public void actionPerformed(ActionEvent a){
Object obj = a.getSource();
if(obj instanceof JButton){
JButton bChecker = (JButton)obj;
if(bChecker == but1){
JOptionPane.showMessageDialog(null, "You clicked But 1" );
//do what you want when but 1 is clicked
}
else{
JOptionPane.showMessageDialog(null, "You clicked But 2" );
//do what you want when but 2 is clicked
}
}
}
public static void main(String[] a){
NewClass n = new NewClass();
}
}//end of class
Top-level Listeners(cont)
Top-level Listeners(cont)
0 Using one listener makes the response slower, and forces all events to
be handled in the same place. This uses the event model which was
introduced in Java 1.1, but it has all the problems of the old Java 1.0
event model. Although you will see this style used in some Java
books, don't use it. It doesn't scale up from one control to many.
Buttons, menu items, toolbar items, etc use action listeners; imagine
what this method would look like for Microsoft Word!
0 Grouping all separate action listeners together in the source code is a
good idea to make the code more comprehensible, but don't try to put
all processing in one method!
Action, AbstractAction
0 The javax.swing.Action interface, and the corresponding
class, javax.swing.AbstractAction, provide a useful mechanism to
implement action listeners that can be shared and coordinated.
Actions can be used with most buttons, including toobox buttons
and menu items, text fields, etc.
They can be shared with all controls which do the same thing.
Actions can be dis-/enabled, and they will then dis-/enable all
corresponding controls.
They can specify text, icons, tooltip text, accelerator, and mnemonic
keys.
0 Subclassing. You must subclass AbstractAction (the hint is the word
"abstract" in the class name). The minimum you need to do is
override actionPerformed(...) to specify what you want the Action to
do. See examples below.
Action, AbstractAction(cont)
Constructors for abstract classes?
0 At first it seems impossible that there should be a constructor
for an abstract class because it's not possible to actually create
an object of an abstract class type. The Java syntax for
anonymous classes allows an abstract class's constructor to be
called if it is followed by the body for the anonymous class.
See Example - Simple anonymous class below.
Action, AbstractAction(cont)
AbstractAction constructors, methods, and fields
Constructors
act = new AbstractAction(String name) {...} Specifies name for button, etc. Must
defineactionPerformed(...) in body.
act = new AbstractAction(String name, Specifies name and an icon (eg, that
Icon smallIcon) {...}; will appear on a toolbar buttons). Must
define actionPerformed(...) in body.
Some Methods
b = act.isEnabled() Returns true if this Action is enabled.
act.setEnabled(boolean enabled) Sets the status of this Action.
act.putValue(String key, Objectvalue) Sets the value of property key to value.
obj = act.getValue(String key) Gets the value of property key.
When clicked :-
getSelection() method of ButtonGroup class.
public class JRadioButtonAction implements ActionListener {
ButtonGroup myGroup = null;
JLabel myLebal = null;
If you press the "On" button and hold it, you will see 2
messages showing in command window. If you release the
"On" button, you will see 5 more messages. If you continue to
press the "Off" button and hold it, you will see 2 more
messages. If you release the "Off" button, you will see 7 more
messages. Here is the list of all the messages:
ActionListener, ChangeListener and
1: State changed on - On
ItemListener
2: State changed on - On - "On" pressed
3: State changed on - On
4: Item state changed - On
5: State changed on - On
6: Action performed - On
7: State changed on - On - "On" released
8: State changed on - Off
9: State changed on - Off - "Off " pressed
10: State changed on - On
11: Item state changed - On
12: State changed on - Off
13: Item state changed - Off
14: State changed on - Off
15: Action performed - Off
16: State changed on - Off - "Off " released
0 Action event raised only once when you release a button.
0 Change event (stateChanged method call) is raised 2 times when you press a button; and
raised 2 time again when you release a button. This tells us that a button has more than 2
states: selected and deselected.
0 Item event (itemStateChanged method call) is raised only once when you release a
button.
0 In a button group, if one button is selected, other selected buttons will be deselected.
Events #10 and #11 show that when "Off" is selected, "On" is deselected.
Button Action Handler at the Component Level
public class JButtonAction1 {
public static void main(String[] a) {
JFrame f = new JFrame("My Switch Button");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new MyButton();
f.getContentPane().add(b);
f.pack();
f.setVisible(true);
}
private static class MyButton extends JButton implements ActionListener {
String text = "On";
public MyButton() {
super();
setText(text);
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (text.equals("On"))
text = "Off ";
else
text = "On";
The button works well. If you click
setText(text); the button, the button label text
} will change from "On" to "Off"; and
} from "Off" to "On", if you click it
} again.
Button Action Handler at the Frame Level
public class JButtonAction2 implements ActionListener {
JButton myButton = null;
JLabel myLebal = null;
String text = null;
public void createFrame() {
JFrame f = new JFrame("My Switch Button");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = f.getContentPane();
c.setLayout(new GridLayout(2,1));
text = "On";
myButton = new JButton(text);
myButton.addActionListener(this);
c.add(myButton);
myLebal = new JLabel(text,SwingConstants.CENTER);
c.add(myLebal);
f.pack();
f.setVisible(true);
} The button works nicely. If you
click the button, the button label
//cont…. text will change from "On" to "Off",
and the text of the label component
will also change.
Button Action Handler at the Frame Level
//….cont
public static void main(String[] a) {
JButtonAction2 myTest = new JButtonAction2();
myTest.createFrame();
}
public void actionPerformed(ActionEvent e) {
if (text.equals("On"))
text = "Off";
else
text = "On";
myButton.setText(text);
myLebal.setText(text);
}
}
0 You can also get a list of the system fonts on the host computer.
See below.
Font(cont)
Constructor
Example
JButton b = new JButton("OK");
b.setFont(new Font("sansserif ", Font.BOLD, 32));
Font(cont)
Available system fonts
0 For maximum portability, use the generic font names, but you can use any font
installed in the system. It is suggested to use a font family name, and create
the font from that, but you can also use the fonts directly. You can get an array
of all available font family names or all fonts.
Font f;
f = new Font(String name, int style, int size); // creates a new font
Example
Font big = new Font("SansSerif", Font.Bold, 48);
...
g.setFont(big);
g.drawString("Greetings Earthling");
Font(cont)
Using Fonts for Graphics
Font f;
f = new Font(String name, int style, int size); // creates a new font
Example
Font big = new Font("SansSerif", Font.Bold, 48);
...
g.setFont(big);
g.drawString("Greetings Earthling");
Font(cont)
Unicode fonts
0 If you're running a recent version of Windows, you probably already have a
Unicode font installed, Arial Unicode MS, which is a very extensive Unicode
font. If you're not running windows, you can get a the Bitstream Cyberbit font,
which is quite complete (about 30,000 characters), but lacks a few of the the
lesser used characters (eg, Old Cyrillic).
0 Windows installation instructions:
1. Download from
ftp://ftp.netscape.com/pub/communicator/extras/fonts/windows/Cyberb
it.ZIP [6.3MB Zipped]. It's also available other places on the Internet. It was
originally written by Bitstream, but they no longer offer it for free
download.
2. Unzip into a temporary directory.
3. Start the Fonts control panel, and add Bitstream Cyberbit font from that
directory.
Look and Feel
0 Look and Feel is the term for the general appearance of GUI
components. Java allows you to change it.
0 System vs portable L&F. The default L&F is the Java portable look and
feel. A popular choice is to use the current system look and feel (eg,
Windows or Macintosh).
0 Non-standard. You can use independent L&Fs to give the user a
particular experience. See below.
0 Start of main(). If you set the look and feel, put it as the first thing in
main().
Look and Feel
Default cross-platform Look and Feel
0 Java cross-platform Look & Feel is the default, so you don't have to set it. This
is the most portable.
Look and Feel
System Look and Feel
0 Some think the user experience is better when a program matches the system
L&F, eg, on Windows the program has a Windows L&F (as in the example
below), on the Macintosh it will use the standard Macintosh L&F. The only
change to the code that produced the sample above was to set the L&F. The
components have a different shape, size, and appearance.
Look and Feel
System Look and Feel
0 Here's how to use the System L&F. Be sure it's the first thing in main.