Swings: Made By: Chaya Malik Karan Narula
Swings: Made By: Chaya Malik Karan Narula
Made by:
Chaya Malik
Karan Narula
Swing is a set of classes that provides more powerful and flexible
components than are possible with the AWT.
in Swing
For example, a button may have both an image and a text string
associated with it.
Also,the image can be changed as the state of the button
changes.
Unlike AWT components, Swing components are not implemented
by platform specific code.
Swing does all that AWT does, but better and there’s much more
of it.
Java Swing class hierarchy
CODING WITH SWINGS
At the start of your code - always
import javax.swing;
import javax.swing.event;
Most Swing programs also need
import java.awt.*;
import java.awt.event.*;
STEPS TO BUILD A GUI
1.import package
3.apply layout
4.add components
(e.g. Label, Button)
5.REGISTER listeners
Layout: BorderLayout
3. apply layout
(e.g. BorderLayout)
4. add components
(e.g. Label, Button)
5. REGISTER listeners
Top-level container:
place for other Swing components to paint themselves
e.g., JFrame, JDialog, Japplet
Intermediate container:
simplify positioning of atomic components
e.g., JPanel, JSplitPane, JTabbedPane
Atomic components:
-self-sufficient components that present information to and get input
from the user
-e.g., JButton, JLabel, JComboBox, JTextField, JTable
• Unlike ‘passive’ containers, controls are the ‘active’ part of your
GUI
• Controls are event sources !
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
Components
JFrame
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(“pressme”);
p.add(b);// add button to panel
f.setContentPane(p);
// add panel to frame
f.show();
}
}
press me
Layout Manager Heuristics
Null Flow Layout Grid Layout
none,
Left to right,
programmer
Top to bottom
sets x,y,w,h
s
COMPONENTS
Japplet
The first form uses the image in the file named filename.
The second form uses the image in the resource identified by
url.
The ImageIcon class implements the Icon interface that
declares the methodsshown here:
Method Description
int getIconHeight( ) Returns the height of the icon in pixels.
The icon and text associated with the label can be read and written by the
following methods:
Icon getIcon( )
String getText( )
void setIcon(Icon i)
void setText(String s)
Here, i and s are the icon and text, respectively
Text Fields
The Swing text field is encapsulated by the JTextComponent class, which
extends JComponent.
provided if necessary.