Java - Swing (from 21 Days)
Refererences and Links.
-----Jul/08/2002 MON: Swing Constants
Notes.
DAY 8: Working with Swing. (pg.195-221: 27 pages)
- SimpleFrame.java
// SimpleFrame.java ********************************************************
import javax.swing.JFrame;
public class SimpleFrame extends JFrame {
public SimpleFrame() {
super("Frame Title");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] arguments) {
SimpleFrame sf = new SimpleFrame();
}
}
// end SimpleFrame.java ****************************************************
-----Dec/06/2002 FRI: DAY 8: Working wiiith Swing
===Introduction (pg.195)
- Swing is part of the JFC (Java Foundation Classes).
- Swing is an extension of AWT (Abstract Window Toolkit).
(Note: AWT is part of the JFC.)
- Swing provides graphics. Takes inputs from keyboard, mouse, etc.
===CREATING AN APPLICATION (more Intro) (pg.196)
- "Swing components, unlike their predecessors in previous versions of Java,
are implemented entirely in Java. This makes them more compatible across
different platforms than the AWT".
[-]Q: Does this mean, A) Swing components (in this new version)?, or
B) previous versions of Java (did not have swing)?
Answer Is Probably: (A) New Swing is written entirely in Java.
[*]Q: Did Swing exist before version Java 2? (Yes, according to next note)
- Caution: Name eventualy settled on by Sun: javax.swing.
Names such as com.sun.java.swing or java.awt.swing, may need changed for
use in Java 2.
- Two other packages for graphical user interfaces:
1) java.awt - Abstract Window Toolkit.
2) java.awt.event - User input event-handling classes.
[*]Dec/06/2002 FRI: What does this error mean?
What caused this error?____
D:\My\Java\21Days\week2>javac SimpleWindow.java
D:\My\Java\21Days\week2>java SimpleWindow.java
Exception in thread "main" java.lang.NoClassDefFoundError: SimpleWindow/java
ANSWER: Solved when adding CLASSPATH to batch file:
set classpath=D:\My\Java\21Days\%1
-----Dec/09/2002 MON: DAY 8: Working wiiith Swing (pg.197)
- CREATING A SWING COMPONENT, 1) call constructor method to create an object,
2) call component's methods for other setup.
- "All Swing components are subclasses of the abstract class JComponent"
- Some Component Factors: size, color, font, tooltips.
- Caution: Often better not to mix Swing Components with AWT Components.
"There's a Swing component for every AWT component."(see pg.197)
- To use a swing component, it must be added to a container component.
- Swing container classess are subclasses of java.awt.Container.
- Can often be placed in other containers.
- java.awt.Container - a class in the Abstract Window Toolkit.
- Has methods to adjust components such as: add them, remove,
arrange (w/layout manager), set up empty insets on edges.
===Creating an Interface (1st Step) (pg.197)
- 1st Step: Create "a class that represents the graphical user interface".
- Use this class to create a container object.
- Many times the container will be from the class JWindow or JFrame
(,JApplet, or JPanel).
- Windows DON'T have: a title bar, max-min-close buttons, etc.
- Example: At an aps load time, Windows can display logos, etc. (pg.198.top)
- Frames are Windows that DO have: a title bar, max-min-close buttons, etc.
- Constructor method should do the four things displayed in "SimpleFrame.java"
(in following notes).
===Developing a Framework (a small sample ap) (pg.199)
- [FILSIZ..MAIN.(PAGE).FILE-DESCRIPTION....................]
- SimpleFrame.java 364 yes (200) Miminal JFrame Swing application
- SimpleWindow.java 447 yes (201) JWindow verses JFrame
- ExitWindow.java 164 no (203) "WindowAdapter" sample code
- ExitFrame.java 380 yes (204)
- Buttons.java 602 yes (206) JButtons to a JFrame's content pane
- ButtonApplet.java 388 no (207) "Buttons.java" rewritten as an applet
- Icons.java 614 yes (209) Places gif files on JButtons as icons
(Free Icons to use in projects.)
- Form.java 993 yes (213) JTextField, JPasswordField, JTextArea, JLabel
- AskPassword.java 1,078
- ChooseTeam.java 849 yes (217) Ap w/4 radio buttons in a group
- Expiration.java 799
- Labels.java 730
- VCR.java 763
13 File(s) 8,171 bytes
- SAMPLES FROM 'JAVA IN 21 DAYS' ('Y' file contains "main()")
- // ***********************************************************************************
// SimpleFrame.java - (One way to make a Swing ap: make interface a subclass of JFrame)
// Sams: Teach Yourself Java 2 in 21 Days by Laura Lemay and Rogers Cadenhead (pg.200)
// http://www.cadenhead.info/book/java21/
import javax.swing.JFrame;
public class SimpleFrame extends JFrame {
// Needs a Constuctor method to do: A, B, C, and D...
public SimpleFrame() {
super("Hello World"); // A) Call constructor of superclass (JFrame).
setSize(300, 100); // B) Set size of frame, in pixels.
// C) Handle user - Close of Window.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // D) Display the frame. Or call show();
}
// ...
public static void main(String[] arguments) {
// 1) Call constructor method to create an object
SimpleFrame sf = new SimpleFrame();
// 2) Call component's methods for other setup
// ...(none in this case)
}
} // *********************************************************************************
- JWindow is the same as JFrame minus a title bar, max-min-close buttons, etc.
===Closing a Window (event handling) (pg.202)
- setDefaultCloseOperation()
- It is a method introduced in Java 2. It reduces code needed for close an ap.
- Belongs to following three classes:
1) javax.swing.JFrame.setDefaultCloseOperation(int)
2) javax.swing.JDialog.setDefaultCloseOperation(int)
3) javax.swing.JInternalFrame.setDefaultCloseOperation(int)
- Components for monitoring a window and handling events: (MORE:Day11)
A) Objects that implement the WindowListener interface can monitor a window.
- "To implement an interface, a class must include all the methods in that
interface."
- For a class to support WindowListener, it must have seven specific methods,
that handle user interactions with the window. (see pg.203)
B) class WindowAdapter (part of java.awt.event.package) implements
WindowListener with empty methods for the seven specific methods.
- ExitWindow.java, sample file, creates a subclass of WindowAdapter to
override desired methods. ExitWindow objects can monitor frames.
C) Call a frame or window's addWindowListener() method to associate listener objects
with the frame or window. See ExitFrame.java (see pg.204)
- // Example to combine components invovled in event handling...
JFrame myFrame = new JFrame("Monitoring a window and handling events.");
ExitWindow frameMonitor = new ExitWindow();
myFrame.addWindowListener(frameMonitor);
- All java's event handling is in java.awt.event package.
- This shows how java handles user input within Swing. (MORE:Day11)
To close a graphical ap, prior to Java 2, a program had to:
1) "Create an obj that will monitor the state of the window."
2) "Implement an interface in the obj that handles each way the window can change."
3) "Associate the window with your user interface."
- /*************************************************************************
*** From: JavaTM 2 SDK, Standard Ed. Documentation (Ver 1.4.0) ***********
===java.awt.event . Interface WindowListener
- extends EventListener
- The listener interface for receiving window events. The class
* The class that is interested in processing a window event EITHER:
1) implements this interface (and all the methods it contains) OR
2) extends the abstract WindowAdapter class (overriding only the
methods of interest).
- The listener object created from that class is then registered with a
Window using the window's addWindowListener method. When the window's
status changes by virtue of being opened, closed, activated or
deactivated, iconified or deiconified, the relevant method in the
listener object is invoked, and the WindowEvent is passed to it.
Since: Ver 1.1
**************************************************************************
===java.awt.event . class WindowAdapter
- extends Object
- implements WindowListener, WindowStateListener, WindowFocusListener
- An abstract adapter class for receiving window events. The methods in
this class are empty. This class exists as convenience for creating
listener objects.
*************************************************************************/
===Adding Components to a Container (pg.205)
- Creating a Component pg.204
- Each instance of JButton is one button component. Each can be added to a container.
[ ]Q: Can one button obj be added to different containers at the same time?
- All Swing's user interface components are subclasses of java.awt.Component.
- JPanel is simplest container.
- In order to display components, they need to be added into a container.
- Add components to simple containers (like JPanel) with container's add(myButton).
- Other containers extricate into sub containers called panes.
- Examples of these more complex containers are frames, windows, applets, and
dialog boxes.
- Components are usually added to a complex container's content pane.
// Example:
JFrame myFrame = new JFrame("Hi"); // Creates a complex container.
JPanel myPanel = new JPanel(); // Creates a simple container.
myPanel.add(myButton1); // Adding component to simple container.
myFrame.setContentPane(myPanel); // Adding to complex container.
- See Buttons.java, sample of JButtons to a JFrame's content pane. (pg.206)
Be careful here to realize that Buttons, in this sample, is a container,
not a component. (These buttons do nothing until adding things learned on Day11 (4thSwingDay))
===Adding Components to an Applet (pg.207)
- Java 2 adds components to the applet's content pane.
- In the Applet's init() method:
1) Create a new JPanel.
2) Add buttons to the new panel.
3) setContentPane(theNewPanel);
- Java 1.0 and 1.1 adds components directly to the applet using add().
Java 1.0 and 1.1 applets are subclasses of java.applet.Applet.
===WORKING WITH COMPONENTS (pg.208)
- All Swing classes are subclasses of javax.swing.JComponent. You will find some of
JComponent's methods to be very useful.
- Components are enabled by default. When a component is disabled, its appearance may
change to gray text, for example. Use setEnabled(boolean) and isEnabled().
- Component visibility works the same as it does for containers. Use setVisible(boolean)
and isVisible().
- Component's defualt size usually good enough. You can use setSize(int,int),
setSize(Dimension) and getSize(). (pg.209)
- Other useful methods for Swing components: setText(), getText(), setValue() and
getValue().
===Image Icons (pg.209)
- Icons usually in GIF format.
- Icons may be placed on buttons, labels, and other's for identification.
- Note comparison of ImageIcon and Icon:
/*************************************************************************
*** From: JavaTM 2 SDK, Standard Ed. Documentation (Ver 1.4.0) ***********
===javax.swing.Icon // (Interface)
- All Known Implementing Classes:
..., ImageIcon, ...
- public interface Icon
- A small fixed size picture, typically used to decorate components.
**************************************************************************
===javax.swing.ImageIcon // (class extended from java.lang.Object)
- All Implemented Interfaces:
Accessible, Icon, Serializable
- public class ImageIcon // class
implements Icon, Serializable, Accessible // interfaces
- An implementation of the Icon interface that paints Icons from Images.
Images that are created from a URL or filename are preloaded ...
(Note: A class in an implementation of an interface. [ ]Q: What does
this mean?)
- (More info and examples) How to Use Icons (in Sun's Java Tutorial).
- Warning: Serialized objects of this class will not be compatible with
future Swing releases. ...
*************************************************************************/
- // Sample Code:
ImageIcon myIcon = new ImageIcon("myIconPic.gif");
JButton myButton = new JButton(myIcon); // Casting not needed here.
JPanel myPane = new JPanel(); // [ ]Q: Does that mean, ImageIcon (class)
pane.add(myButton); // must be smaller than Icon (interface)?
setContentPane(myPane);
- Icons.java - Places gif files on JButtons as icons. Adds buttons to a panel. Then sets
the panel to be the frame's content pane. (pg.209)
- This Zeldman page offers free icons to use in your own projects.
===Lables (pg.210)
- Labels are not editable by the user. They can contain text and/or an icon.
- The programmer can specify alignment of the label:
LEFT, CENTER (the default), and RIGHT are from the SwingConstants interface.
- Other JLabel methods: setText(String), setIcon(Icon), getText(), and getIcon().
===Text Fields (pg.211)
- By text fields, users can enter and modify from the keyboard.
- JTextField is the name of the class for one-line of input.
- Text field contents can be initialized.
- Direct known subclasses of javax.swing.text.JTextComponent are:
1) JEditorPane, 2) JTextArea, and 3) JTextField.
- JTextField width attribute, only effective if not automaitically resizing.
===Text Areas (pg.212)
- JTextArea is used to handle multi-line text editing.
- Some useful methods for both JTextArea and JTextField classes, from there common
superclass, JTextComponent are: getText(), getSelectedText(), and setText().
- Two methods in class JTextArea (not in JTextField) are:
void append(String str)
void insert(String str, int pos)
- Control line-wrap and wrap-style:
void setLineWrap(boolean wrap) - true=On and false=Off.
void setWrapStyleWord(boolean word) - true=ByWord and false=ByCharacter.
- Form.java - public class Form extends javax.swing.JFrame {...}
1) The text fields and areas are made as instance variables to the Form object.
a) So each new Form will get its own text fields and areas.
b) Text fields and areas are accessable to all methods of the Form class.
2) Form's constructor:
a) Creates a JFrame by calling super().
b) Sets the frame's size and default close option.
c) Adds swing components to a JPanel pane which becomes the frames's content pane.
d) Then show()s the frame.
3) The third portion of our class is a main() method:
public static void main(String[] arguments) {
Form input = new Form();
}
===Scrolling Panes (pg.214) - Notes from next day (Day 9).
- Swing has JScrollPane class. That is why most, or all, other Swing components do not
offer scrolling. Scrollable view for a lightweight component (but not heavyweight).
[-]Q: Does 'heavyweight' mean 'complex'? (probably, yes)
- How to Use Scroll Panes, a section in The Java Tutorial.
- Constructors can include these parameter values:
HORIZONTAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER, and
VERTICAL_SCROLLBAR_ALWAYS, VERTICAL_SCROLLBAR_AS_NEEDED, VERTICAL_SCROLLBAR_NEVER
- After creating a scrolling pane that contains a component, then add the scrollPane to
simple container(s).
- // Example:
JPanel myJPanel_pane = new JPanel(); // Creates a simple container.
JTextArea myJTextArea_comments = new JTextArea( 4, 15 );
JScrollPane myJScrollPane_scroll = JScrollPane( myJTextArea_comments );
myJPanel_pane.add( myJScrollPane_scroll ); // Before, components where added.
setContentPane( myJPanel_pane ); // AddSimpleContainerToComplexContainer (sameAsBefore).
===Scrollbars (pg.215)
- Scrollbars are simply components that return a value. int getValue().
- The constructor with the most parameters is the following:
public JScrollBar(int orientation, - (dflt: JScrollBar.VERTICAL)
int value,
int extent, - size of viewable area. Also known as "visible amount". (sun)
If zero, then a default size is used.
int min,
int max)
===Check Boxes and Radio Buttons (pg.216)
- Check Boxes and Radio Button components are the same in all ways except appearance.
- The swing class names are JCheckBox and JRadioButton.
- Each can have a value of checked or not checked.
- And both may be grouped so that only one is allowed to be checked at a time.
- Their common superclass offer these methods: setSelected(boolean) and isSelected().
- ButtonGroup class is used to allow only one to be selected at a time. Just create an
instance of ButtonGroup, and add() check boxes or radio buttons to the group object.
- ChooseTeam.java is a sample ap with four radio buttons in a group. (pg.217)
===Drop-Down Lists and Combo Boxes (pg.218)
- The swing class, JComboBox, can produce both Drop-down lists (also called choice lists)
or combo boxes.
- Combo boxes are drop-down lists with an added ability to input text. To add this
ability to a drop-down object, call the JComboBox's setEditable(true) method.
- Expiration.java
===Summary (pg.220)
- "...can be complex, and Swing represents the largest package of classes that a new Java
programmer must deal with..."
- Since Sun Micro designed Swing with many common superclasses, its easier to understand.
- Component's fonts can be changed by using JComponent's setFont(Font) method.
- Days 8 and 9, of this study, introduce Swing components.
DAY 9: Building a Swing Interface.
- Graphical user interfaces can be challenging to program, but these applications are more
friendly to the end users. Java programmers coding is made less difficult by using the
set of classes called Swing.
===SWING FEATURES (pg.224)
- Day 8 covered Swing classes which, for the most part, are improved features of AWT.
- Swing also adds new features for keyboard, look-and-feel, tool-tips, and dialog-boxes etc.
===Setting the Look and Feel (pg.224)
- UIManager Swing class to set look and feel. Three UIManager choices within the Windows
environment.
- // Sample code.
public static void main(String[] arguments) {
// Jan/01/2003 WED
try {
// UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.err.println("Can't set look and feel: " + e);
}
Expiration ct = new Expiration(); // from Expiration.java
}
===Standard Dialog Boxes (pg.225)
- JOptionPane contains these four methods to provide dialog boxes without having to code a
new class for dialog boxes you include in your applications.
- JOptionPane class can seem complex because of its many methods. But most of its uses are
simply one-line calls to one of JOptionPane's static methods:
1) showConfirmDialog() - Asks a yes/no/cancel question. Returns int that user selects.
2) showInputDialog() - Prompt for user input. Returns String that user input, or null.
3) showMessageDialog() - Tell user a message. Returns void.
4) showOptionDialog() - The Grand Combination of above three. Returns int chosen, or
CLOSED_OPTION if the dialog was closed.
- Info.java - Example application with JOptionPane dialog boxes. Contains main(). (pg.229)
===Sliders (pg.232)
- JSlider allows a user to set an int value.
- Programmer can set major and minor tick spacing. Call these mehtods before adding the
slider to the container.
- Slider.java - Creates a slider and sets its tick marks. Contains main(). (pg.233)
===Scroll Panes (pg.233) - Notes from previous day (Day 8).
NewRule1) JScrollPane is a container, to which a component must be added to be able to
scroll the component.
NewRule2) Then the scroll-pane is added to a simple pane, such as a JPanel.
- If you call the setPreferredSize() (superclass) method is called, it should be done
before adding the scroll-pane to the container.
- Vertical and horizontal scrollbar policies' default are to display them only when
needed. Different policies may be choosen with the objects constructor method.
===Toolbars (pg.235)
- JToolBar creates a container. Usually contain buttons.
- Append components into toolbar containers with add() method.
public Component add(Component comp) - From class java.awt.Container.
- This is a convenience method for:
addImpl(java.awt.Component, java.lang.Object, int).
- JToolbar can be made dockable by using BorderLayout manager.
[ ]Q: Are these two sentences of the book acurate (on pg.235.bottom)? "The toolbar
should be placed in one of the directional areas of the border layout. The only
other area that can be filled is the center."
- Looking ahead: Class JToolBar's add(Action a) method is not recomended with Java 1.3.
With Java 1.3, "to configure a control with an action using setAction, and then add
that control directly to the Container." (sun) setAction is found in:
- javax.swing.AbstractButton.setAction(javax.swing.Action)
- javax.swing.JComboBox.setAction(javax.swing.Action)
- javax.swing.JTextField.setAction(javax.swing.Action)
- org.w3c.dom.html.HTMLFormElement.setAction(java.lang.String)
- ToolBar.java - Sample text editor with toolbar. JFrame, ImageIcon, JButton, JToolBar,
JTextArea, JScrollPane, JPanel, JTextArea, BorderLayout. Contains main(). (pg.236)
===Progress Bars (pg.237)
- JProgressBar can display progress of a task being run.
- SwingConstants.VERTICAL, and SwingConstants.HORIZONTAL to select its orientation.
- public void setValue(int n) - immediately updates the display.
- public void setStringPainted(boolean b) - "determines whether the progress bar should
render a progress string". (sun)
===Summary (pg.240)
- This day's chapter shows how to create more Swing components and add them to containers.
- BorderLayout manager can provide framework for dockable toolbars.
- Day 10, covers: Arranging Components on a User Interface.
- Day 11, covers: Responding to User Input.
DAY 10: Arranging Components on a User Interface. (pg.243: 25 pages)
- To this point, in this study, we know how to put components into containers, but do not
know much about controling their location.
- This chapter covers five layout managers (classes). (help with component arrangment)
- Sometimes two or more of these classes (layout managers) can be used together.
===Basic Interface Layout (pg.244)
- Java laysout components in a fluid maner. Discussed on page 244.
- "Some Java development tools" allow control similar to Microsoft Visual C++'s or Visual
Basic's co-ordinate coding, "through the use of their own windowing classes. (P#) When
using Swing, a programmer gains more control over the layout of an interface by using
layout managers."
===Laying Out an Interface (pg.244)
- FlowLayout is the default for panels.
- BorderLayout is the default for frames, windows, and applets.
- Other layout mgr classes are: GridLayout, CardLayout, and GridBagLayout.
- Use following method from class java.awt.Container, to assign container's layout:
public void setLayout(LayoutManager mgr);
LayoutManager mgr - Instance of one of the layout managers.
- Set a container's layout mgr before add()'ing any components to the container.
===Flow Layout (pg.245)
- A container set to FlowLayout, its components flow from left to right, and new lines
are created when needed.
- By default, components are centered, and are separated by three pixels horizontally
and three pixels vertically.
- Constants that may be used in constructor: FlowLayout.LEFT (and CENTER, and RIGHT).
- Example: Alphabet.java - (pg.245)
===Grid Layout (pg.247)
- GridLayout also are added from left to right etc (similar to FlowLayout).
- Each components is displayed in a grid cell. (instead of centered and so on)
- The gap default is zero pixels horizontally and vertically.
- Sample constructor:
public GridLayout(int numRows,int numColumns,int HorzGap,int VertGap);
- Example: Bunch.java - (pg.247)
===Border Layout (pg.249)
- BorderLayout divides a container into five areas, North, South, East, West, and Center.
- The center gets the space left over.
- Component add(String name, Component comp); // for java.awt.Container
The first parameter of the add() method is a string, such as "North", or "South".
The second parameter is the component to add to the container.
- Example: Border.java - (pg.250)
===Mixing Layout Managers (pg.250)
- To mix layout managers, you need to add panel containers, to main containers. Use JPanel
class to create panel objects. Two things to remember about panels: 1) Add the components
to panel before putting it in larger container, and 2) Each panel gets its own layout mgr.
- Tip: Start with the outermost panel first, then work inword. (day11.pg283)
===Card Layout (pg.251)
- Card layouts are different than other layouts.
- Card layouts group together containers or components, and displays one at a time.
- These are used with Tabbed interfaces. Each tab displays what is called a card.
- Component add(String name, Component comp); // for java.awt.Container
The first parameter gives a name to the card.
The second parameter is the component to add to the container.
- Use java.awt.CardLayout's show() method to display a card by name.
void show(Container parent, String name);
===Grid Bag Layout (pg.253)
- GridBagLayout is like GridLayout except for three points:
1) A component can consume more than one grid cell.
2) "The proportions between different rows and columns do not have to be equal."
3) "Components inside grid cells can be arranged in diffent ways."
- To use GridBagLayout it should be used together with GridBagConstraints. The job of
GridBagConstraints is to assign properties to each component.
- The following is the basic steps to make a GridBagLayout:
1) Make a GridBagLayout object and myContainer.setLayout(myGridBag) as with other layouts.
2) Make a GridBagConstraints object.
3) Set up a components constraints.
4) Inform your GridBagLayout of the component and its constraints.
5) Add component to container.
- // Example code to add a single button. (pg.253)
// Steps 1-2.
GridBagLayout myGridBag = new GridBagLayout();
GridBagConstraints myGBConstraints = new GridBagConstraints();
getContentPane().setLayout(myGridBag);
// Step 3.
JButton button1 = new JButton("B1");
myGBConstraints.gridx = 0;
myGBConstraints.gridy = 0;
myGBConstraints.gridwidth = 1;
myGBConstraints.gridheight = 1;
myGBConstraints.weightx = 30;
myGBConstraints.weighty = 30;
myGBConstraints.fill = GridBagConstraints.NONE;
myGBConstraints.anchor = GridBagConstraints.CENTER;
// Steps 4-5. (myGBConstraints may then be reused for the next component)
myGridBag.setConstraints(button1,myGBConstraints);
- The book's NamePass.java sample, contains a useful helper method, buildConstraints().
Paste it into your code to make using constraints easier. The method reminds you of each
constraint and reduces typing.
void buildConstraints(GridBagConstraints gbc, int gx, int gy,
int gw, int gh, int wx, int wy) {
gbc.gridx = gx; // X-cell-coordinate for left edge of Component's display area's.
gbc.gridy = gy; // Y-cell-coordinate for top edge of Component's display area's.
gbc.gridwidth = gw; // Num of cell-columns the component's display area will span.
gbc.gridheight = gh; // Num of cell-rows the component's display area will span.
gbc.weightx = wx; // Specifies how to distribute extra horizontal space.
gbc.weighty = wy; // Specifies how to distribute extra vertical space.
}
// How it would be used in "Step 3" (in above example to add a single button):
// buildConstraints(myGBConstraints, 0, 0, 1, 1, 30, 30);
===Designing the Grid (pg.254)
- Placing components in cells:
- One cell can have no more than one component.
- One component can consume more than one cell in x or y directions.
- Cell coordinates:
- The coordinates of the top-left-most cell is zero, zero.
- The X-coordinate specifies left-to-right, and the Y-coordinate top-to-bottom.
===Creating the Grid (pg.255)
- After designing the Grid on paper, focus on layout.
- Determine the total number of rows and columns needed for your grid.
- Determine if any components will span multiple rows or columns.
- Adjust proportions and alignment later.
- Idea: Use buttons as initial placeholders when designing the layout.
- Layout takes place in the aps constructor.
===Determining the Proportions (pg.258)
- weightx and weighty are int values are used to set a cells width or height by compairing
it to the total weightx or weighty. If a total is 100, the concept could be thought
of like precentages.
- Only one cell per row, and one per column, should have non-zero weights. Zero means,
take the size of the rest of the row.
- Spanning rows or columns should have zero weight for that dimension.
- Expect to adjust the weights by trial-and-error.
===Adding and Arranging the Components (pg.260)
- fill and anchor constraints, adjust the arangment of components within the cell.
- fill - controls stretch of a component in x and/or y direction.
Values: GridBagConstraints.BOTH, NONE (default), HORIZONTAL, and VERTICAL.
- See NOTE on pg 261, for description of general thought behind this layout.
- anchor - controls positioning of a components smaller than the cell.
Values: GridBagConstraints.CENTER (dflt), NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH,
SOUTHWEST, WEST, NORTHWEST.
- MyGridBag.java - My own GridBag layout learning program. (pg.262)
===Cell Padding and Insets (pg.264)
- ipadx and ipady constraints, control padding around individual components that are smaller
than the cell. Default is no padding.
- The Insets class, determines space around a whole panel.
. In Java 1.02, override insets(). In Java 2, override getInsets().
. (Partial list of) getInsets found in:
java.awt.Container.getInsets()
javax.swing.JComponent.getInsets()
javax.swing.JComponent.getInsets(java.awt.Insets)
javax.swing.JViewport.getInsets()
...
javax.swing.UIManager.getInsets(java.lang.Object, java.util.Locale)
. // Java 2, sample override of this method. (pg.264)
public Insets getInsets()
{
return(new Insets(10, 30, 10, 30));
}
===Summary (pg.265)
- Java does not give direct control to placement of components, but with the use of nested
containers you can get the effect you need.
- All five "layout managers and panels" are now covered.
- Advantage: This works on multiple platforms without modifing the code.
- If you really want to make a component a certain size and placed at a specific
spot, then 1) set the layout manager to null, and 2) use the reshape() method.
- Exercises (pg.267) - MyCalander.java - My answer to both exercises.
1) Create a user interface that displays a calendar for a single month.
2) Create an interface that implements more than one layout manager.
DAY 11: Responding to User Input. (pg.269: 27 pages)
- You can now build a swing interface. It's written with swing components, panels, and layouts.
In this chapter we find out how to add code that listens and responds to the user.
- Event listeners are Swing interfaces that handle events. To implement one: 1) Create
a listener object and 2) Associate it with the frame, window, (or panel?). (REVIEW:Day08)
- New listeners handle action events, mouse events, and more. We will then be able to write
full (java) swing aps.
===Event Listeners (pg.269)
- "Each listener handles a specific kind of event, and a class can implement as many of
them as needed."
- Java's set of eight interfaces known as event listeners:
. ActionLisenter - (such as) a button click.
. AdjustmentListener - scrollbar changes.
. FocusListener - a component getting or losing the focus.
. ItemListener - a change to a check box.
. KeyListener - keyboard entry.
. MouseListener - mouse click, or entering or leaving a component's area.
. MouseMotionListener - all mouse movement over a component.
. WindowListener - window functions min, max, close, move, etc.
- // Sample class that implements two listeners.
import java.awt.event.*; // Satisfies all event listener import needs.
public class WatchAndSelectItem extends JFrame implements FocusListener, ItemListener
{ // ...code for WatchAndSelectItem class goes here... }
- This is the first step in making the class an event listener. Next we need to add a matching
listener to the component. The listener will generate events when the component is used.
===Setting Up Components (pg.270)
- Components call their addxxxxx() methods to add listeners to themselves.
. addActionLisenter() . addAdjustmentListener() . addFocusListener() . addItemListener()
. addKeyListener() . addMouseListener() . addMouseMotionListener() . addWindowListener()
- Remember, component modifications must be done before adding it to a container. This
includes adding listeners.
- All addxxxxx() methods take one parameter, the obj listening for that type of events.
- Interface EventListener has about 75 know "Subinterfaces".
- +-------------------------------------------------------------------------------------+
| Swing Interface - Days 8, 9, 10. |
| |
| WindowListener - Listens to a Window for its seven events. |
| .or. |
| WindowAdapter - Convenience class for creating window lstnr-objs. |
| |
| addXxxxListener() - Component calls its apropriet add method. |
+-------------------------------------------------------------------------------------+
===Event-Handling Methods (pg.271)
- ActionLisenter
- public void actionPerformed(ActionEvent evt) { ... }
. evt.getSource() - Determines what component is performing an action.
. "instanceof" keyword can help check the type of componenent performing an action.
- The book's ChangeTitle.java sample. ActionLisenter handles two JButtons.
LINES OF ChangeTitle.java THAT WHERE ADDED TO RESPOND TO AN ACTION EVENT:
. import java.awt.event.*; // Line 1.
. b1.addActionListener(this); // Line 12.
. b2.addActionListener(this); // Line 13.
. And the whole actionPerformed() method to respond to the event of a button press.
- Using "this" is the same as using the current class.
- "this" must implement the ActionListener interface to handle events from certain components.
===Working with Methods (pg.274)
- Summary of: Package java.awt.event - Lists Listener Interfaces, and Event Classes.
- Will be learning the structure of each event handling method.
. Be watching to learn what methods that may be called within the event handling methods
you write.
. If you need to know which component generated an event, getSource() is always a possible
method call.
. myCurrentEvent.getSource() - This method may be heavily used to determine what component
generated your event.
===Action Events (pg.274)
- Action events origionate from: JButton, JCheckBox, JComboBox, JTextField, or JRadioButton.
- See recent section: Event-Handling Methods, (pg.271).
- ActionListener interface's one method (you may write), takes the following form:
. void actionPerformed(ActionEvent e) - (is called when an action occurs)
{
// your code here
}
- For more info than getSource() provides, use String getActionCommand().
- Change return String for a component by calling setActionCommand(). Multiple components
can return the same string. (this can be useful)
===Adjustment Events (pg.275)
- Adjustment events origionate from: JScrollBar. Clicking on arrows or other parts of the bar.
- To handle scrollbar events, a class must implement the AdjustmentListener interface.
. All Superinterfaces: EventListener
. AdjustmentListener interface's one method, takes the following form:
void adjustmentValueChanged(AdjustmentEvent e)
{ // (your custom code here) }
- "Invoked when the value of the adjustable has changed." (Java 2 SDK SE Devlpr Doc)
- Methods of Class AdjustmentEvent. (all methods and their return values
are listed for this class as an example, for insight purposes):
. Adjustable getAdjustable() - "Returns the Adjustable object where
this event originated."
. int getAdjustmentType() - "Returns the type of adjustment which
caused the value changed event."
. int getValue() - "Returns the current value in the adjustment
event."
. boolean getValueIsAdjusting() - "Returns true if this is one of
multiple adjustment events."
. String paramString() - "Returns a string representing the state of
this Event."
- WellAdjusted.java - Example from 21 Days book.
===Focus and Item Events (pg.278)
===For a class to handle focus events, it must implement the FocusListener interface.
- FocusListener interface's methods are:
. void focusGained(FocusEvent e) { // your code here }
. void focusLost(FocusEvent e) { // your code here }
- (As usual,) e.getSource() determines what obj generated the event (ie,gained/lost focus).
===For a class to handle item events, it must implement the ItemListener interface.
- Item events origionate from: JButton, JCheckBox, JComboBox, or JRadioButton.
- ItemListener interface's methods are:
. void itemStateChanged(ItemEvent e) { // your code here } - (when a key has been pressed)
When an item is selected or deselected by the user:
- e.getItem() Returns (Object) item that was affected by the event (ie,selected/deselected).
- e.getStateChange() Returns (int) ItemEvent.SELECTED, ItemEvent.DESELECTED.
- e.getItemSelectable() - Returns (ItemSelectable) the originator of the event.
- e.paramString() - Returns (String) a parameter string identifying this item event.
- SelectItem.java - Good item event example of combobox from 21 Days book.
// public void itemStateChanged(ItemEvent evt) { ...
. Object source = evt.getSource(); - (As usual,) source is obj that generated the event.
It maybe the JComboBox object.
. Object newPick = evt.getItem(); - newPick is the item added to the combobox.
===Key and Mouse Events (pg.280)
===For a class to handle key events, it must implement the KeyListener interface.
- KeyListener interface's methods are:
. void keyPressed(KeyEvent e) { // your code here } - (when a key has been pressed)
. void keyReleased(KeyEvent e) { // your code here } - (when a key has been released)
. void keyTyped(KeyEvent e) { // your code here } - (when a key has been typed)
- e.getKeyChar() - Return Unicode (char) associated with the key in this event.
Example: key-typed is shift + "a" then the return is the value for "A".
Returns: If no valid Unicode character, then CHAR_UNDEFINED is returned.
- Class KeyEvent has ten methods for use.
===For a class to handle mouse events, it must implement the MouseListener interface.
- Detects mouse clicks, and mouse entering/leaving component's area.
- KeyListener interface has five methods.
. Each method has a MouseEvent parameter.
- MouseEvent has nine of its own methods. These four are emphasised:
. int getClickCount() - Returns the number of mouse clicks associated with this event.
. Point getPoint() - ...the x,y position of the event relative to source component.
. int getX() - ...the horizontal x position...
. int getY() - ...the vertical y position...
===For a class to handle mouse motion events, it must implement the
MouseMotionListener interface.
- This listener's methods also use MouseEvent parameters:
. void mouseDragged(MouseEvent e)
. void mouseMoved(MouseEvent e)
===Window Events (pg.282)
- For a class to handle window events, it must implement the WindowListener interface.
- This listener has seven methods, and they use the WindowEvent parameter:
. For when window is activated, then your "windowActivated(WindowEvent e)" method is run.
. Other methods for: closed, closing, deactivated, deiconified iconified, or opened.
. "windowClosing(WindowEvent e)" runs during close, and can even stop the window close.
- WindowAdapter is a class there for convenience. It implements WindowListener.
===An Example: A Color Converter (pg.282)
- Start with: SimpleFrame2.java
- My version of: SwingColorTest.java and SwingColorControls.java
- Designing the Layout and Subpanels
. Used nested panels, grid layout used in each, except for the color panel.
. The sub-panels (ie, SwingColorControls class) needs a number of instance variables in order to get info
back to the ap. One instance var is "SwingColorTest frame", which is the frame (ie, the parent container).
We will want to call its update(), we write as part of the parent class.
===Designing the Layout and Subpanels (pg.283)
===Converting Between sRGB and HSB (pg.287)
===Handling User Events (pg.291)
- SEE FINISHED Color Converter EXAMPLE: swingcolor.html
. It is the applet version of SwingColorTest.java.
===Summary (pg.295)
********************************************************************************
B19 - Teach Yourself Java 2 in 21 Days. 2nd ed. Lemay and Cadenhead. © 2001.
********************************************************************************
Java Home