Professional Documents
Culture Documents
application
The view that is the visual representation
ofthat data
A controller that takes user input on the
http://java.sun.com/products/plugin/1.4/demos/plugin/jfc/SwingSet2/SwingSet2.html
Mixing AWT & SWING
Mixing AWT and Swing is not a good idea.
AWT components are always on top, and z-
ordering problems catch you in many
unexpected ways. Stick with the AWT or move
completely to Swing.
JFrame
Components go in the "content pane", not
directly in the frame.
Changing other properties (layout manager,
background colour, etc.) also apply to the
content pane.
Access content pane via getContentPane, or if
you want to replace the content pane with
your container (e.g. a JPanel), use
setContentPane.
JFrame (cont’d)
JFrames close automatically when you click on
the close button (unlike AWT Frames).
However, closing the last JFrame does not
result in your program exiting Java. So your
"main" JFrame still needs a WindowListener.
You get Java (Metal) look by default, so you
have to explicitly switch if you want native
look.
JFrame Example-I
import java.awt.*;
import javax.swing.*;
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassNam
e());
} catch(Exception e) {
System.out.println("Error setting native Look & Feel: " +
e);
}
JFrame f = new JFrame("This is a test");
f.setSize(400, 150);
Container content = f.getContentPane();
content.setBackground(Color.LIGHT_GRAY);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
f.setVisible(true);
}
}
Running JFrame Examples- I, II
The JComponent Class
With the exception of top-level containers, all
Swing components whose names begin with "J"
descend from theJComponent class
For example, JPanel, JScrollPane, JButton, and
JTable allinherit from JComponent
GUI Component API
Java: GUI component = class
Properties
Methods JButton
Events
Using a GUI Component
1. Create it
Instantiate object: b = new JButton(“press me”);
2. Configure it
Properties: b.text = “press me”; [avoided in
java]
Methods: b.setText(“press me”);
3. Add it
panel.add(b);
JButton
4. Listen to it
Events: Listeners
Anatomy of an Application GUI
GUI Internal structure
JFrame JFrame
JPanel containers
JPanel
JButton
JButton JLabel
JLabel
Using a GUI Component 2
1. Create it
2. Configure it
order
3. Add children (if container) important
4. Add to parent (if not JFrame)
5. Listen to it
Build from bottom up
Create: Listener
Frame
Panel
JLabel JButton
Components
Listeners
Add: (bottom up)
JPanel
listeners into components
components into panel
panel into frame
JFrame
Code
JFrame f = new JFrame(“title”);
JPanel p = new JPanel( );
JButton b = new JButton(“press me”);
f.show();
press me
Application Code
import javax.swing.*;
class hello {
public static void main(String[] args){
JFrame f = new JFrame(“title”);
JPanel p = new JPanel();
JButton b = new JButton(“press me”);
f.show();
}
} press me
Listen to it
...
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bActionPerformed(evt);
}
....
...
Responding to user actions
Based on an event-handling model
New component eg a button should have a
Listener specified
The Listener object is programmed to respond
to Event objects coming from the component
The Listener object needs to implement the
appropriate interface
Event-handling
when clicked
component eg button
http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html
Containment Hierarchy - Example
Look and Feel (LAF)
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassNam
e());
} catch(Exception e) {
System.out.println("Error setting native LAF: " + e);
}
....
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelC
lassName());
} catch(Exception e) {
System.out.println("Error setting Java LAF: " + e);
}
JLabel
With the JLabel class, you can display
unselectable text and images.
If you need to create a component that displays
a string, an image, or both, you can do so by
using or extending JLabel.
If the component is interactive and has a
certain state, use a button instead of a label.
By specifying HTML code in a label's text, you
can give the label various characteristics such
as multiple lines, multiple fonts or multiple
colors.
HTML in Swing Components
o specify that a component's text has HTML
formatting, just put the <html> tag at the
beginning of the text, then use any valid HTML
in the remainder. Here is an example of using
HTML in a button's text:
label = new
JLabel("<html><h1><b><u>T</u>wo</b><br>lines</h1></html>");
JLabel Example
ImageIcon icon =
createImageIcon("images/middle.gif");
. . .
label1 = new JLabel("Image and Text", icon,
JLabel.CENTER);
//Set the position of the text, relative to
the icon:
label1.setVerticalTextPosition(JLabel.BOTT
OM);
label1.setHorizontalTextPosition(JLabel.CE
NTER); label2 = new JLabel("Text-Only
Label");
label3 = new JLabel(icon);
JLabel Example
http://java.sun.com/docs/books/tutorial/uiswing/components/label.html
Menus
A menu provides a space-saving way to let the
user choose one of several options. Other
components with which the user can make a
one-of-many choice include combo boxes, lists,
radio buttons, spinners, and tool bars.
Example
Creating Menus
/Where the GUI is created:
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
//Create the menu bar. menuBar = new
JMenuBar();
Creating Menus (cont’d)
//Build the first menu.
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAcces
sibleDescription( "The only menu in
this program that has menu items");
menuBar.add(menu);
Creating Menus (cont’d)
//a group of JMenuItems
menuItem = new JMenuItem("A text-only menu item", KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_1,
ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription( "This
doesn't really do anything");
menuItem.setMnemonic(KeyEvent.VK_B);
menu.add(submenu);
Creating Menus (cont’d)
//Build second menu in the menu bar.
menu = new JMenu("Another Menu");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"This menu does nothing");
menuBar.add(menu);
...
frame.setJMenuBar(theJMenuBar);
Using Layout Managers
A layout manager is an object that implements the LayoutManager
interface* and determines the size and position of the components
within a container
As a rule, the only containers whose layout managers you need to
worry about are JPanels and content panes
You can set a panel’s layout manager using the JPanel’s
constructor. For example:
JPanel panel = new JPanel(new BorderLayout());
After a container has been created, you can set its layou tmanager
using the setLayout method. For example:
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
BorderLayout
The FlowLayout class provides a very simple layout manager that is used, by
default, by the JPanel objects
GridLayout