Java Swing
Java Swing
Java Swing
Introduction to Swing
• Package : javax.swing.* ;
• Swing is set of classes which provides more
powerful and flexible components as compare to
AWT.
• Build on top of AWT API and acts as replacement of
AWT API.
• Swing component follows a Model-View-
Controller
• Swing Components are implemented using Java and
so they are platform independent.
• Called lightweight components
Introduction to Swing
Swing Features
• Swing introduces many innovations.
• Borders we can draw borders in many different
styles around components using the setBorder( )
method.
• Graphics Debugging We can use
setDebuggingGraphicsOptions method to set up
graphics debugging which means, that you can
watch each line as its drawn and make it flash.
• Easy mouseless operation: It is easy to connect
keystrokes to components.
• Tooltips We can use the setToolTipText method of
JComponent to give components a tooltip, one of
those small windows that appear when the mouse
hovers over a component and gives explanatory text.
• Easy Scrolling We can connect scrolling to various
components-something that was impossible in AWT.
• Pluggable look and feel We can set the appearance
of applets and applications to one of three standard
looks. Windows, Motif (Unix) or Metal (Standard
swing look).
• New Layout Managers Swing introduces the
BoxLayout and OverlayLayout layout managers.
MVC Architecture
• Software design pattern for software development.
• Model:
• Major function of this layer to maintain the data.
• Database and logic.
• View:
• Used to display full or partial data.
• User Interface
• Controller:
• Control the interaction and communication
between Model and view.
• Communication logic/integration logic
UML Diagram MVC Design Pattern
Difference Between AWT & Swing
• AWT uses Applet and Frame while Swing uses
JApplet and JFrame for GUI.
• AWT is platform dependent code while Swing code
is platform independent.
• Swing has bigger collection of classes and interfaces
as compare to AWT.
• AWT components are Heavyweight where as Swing
components are Lightweight.
• In Swing extra feature to Button: Provide Image.
• Swing provides: Tree, Table, Scrollpanes,
Tabbedpanes, etc. new feature.
• AWT does not follow MVC.
JApplet
• Fundamental to Swing is the JApplet class, which
extends Applet.
• Applets that use Swing must be subclasses of JApplet.
• JApplet is rich with functionality that is not found in
Applet.
• For example, JApplet supports various “panes,” such
as the content pane, the glass pane, and the root
pane.
Various Panes in Java.
Methods
• When adding a component to an instance of JApplet,
do not invoke the add( ) method of the applet
instead, call add( ) for the content pane of the
JApplet object.
• The content pane can be obtained via the method
shown here:
• Container getContentPane( )
• The add( ) method of Container can be used to add a
component to a content pane.
• void add(comp)
• Here, comp is the component to be added to the
content pane.
Icons and Labels
• In Swing, icons are encapsulated by the ImageIcon
class, which paints an icon from an image.
• Two of its constructors are shown here:
• ImageIcon(String filename)
• ImageIcon(URL url)
• 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 methods shown here:
• int getIconHeight( )
• Returns the height of the icon in pixels.
• int getIconWidth( )
• Returns the width of the icon in pixels.
• void paintIcon(Component comp, Graphics g, int x, int y)
• Paints the icon at position x,y on the graphics
context g. Additional information about the
paint operation can be provided in comp.
Swing labels
• Swing labels are instances of the JLabel class, which
extends JComponent.
• It can display text and/or an icon.
• Some of its constructors are shown here:
• JLabel(Icon i)
• JLabel(String s)
• JLabel(String s, Icon i, int align)
• Here, s and i are the text and icon used for the label.
• The align argument is either LEFT, RIGHT,CENTER,
LEADING, or TRAILING these are constants.
• Icon getIcon( )
• String getText( )
• void setIcon(Icon i)
• void setText(String s)
1.import javax.swing.*;
2.class LabelExample
3.{
4.public static void main(String args[])
5. {
6. JFrame f= new JFrame("Label Example");
7. JLabel l1,l2;
8. l1=new JLabel("First Label.");
9. l1.setBounds(50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. l2.setBounds(50,100, 100,30);
12. f.add(l1); f.add(l2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Text Fields
• The Swing text field is encapsulated by the
JTextComponent class, which extends JComponent.
• It provides functionality that is common to Swing
text components.
• One of its subclasses is JTextField, which allows us
to edit one line of text.
• Some of its constructors are shown here:
• JTextField( )
• JTextField(int cols)
• JTextField(String s, int cols)
• JTextField(String s)
1.import javax.swing.*;
2.class TextFieldExample
3.{
4.public static void main(String args[])
5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome to Javatpoint.");
9. t1.setBounds(50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. t2.setBounds(50,150, 200,30);
12. f.add(t1); f.add(t2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Button
• Swing buttons provide features that are not found in
the Button class defined by the AWT. For example,
we can associate an icon with a Swing button.
• Swing buttons are subclasses of the AbstractButton
class, which extends JComponent. AbstractButton
contains many methods that allow us to control the
behavior of buttons, check box and radio buttons.
• For example, we can define different icons that are
displayed for the component when it is disabled,
pressed, or selected.
• Another icon can be used as rollover icon, which is
displayed when the mouse is positioned over that
component.
Methods
• void setDisabledIcon(Icon di)
• void setPressedIcon(Icon pi)
• void setSelectedIcon(Icon si)
• void setRolloverIcon(Icon ri)
• String getText( )
• void setText(String s)
• Concrete subclasses of AbstractButton generate action
events when they are pressed. Listeners register and un-
register for these events via the methods shown here:
• void addActionListener(ActionListener al)
• void removeActionListener(ActionListener al)
• Here, al is the action listener.
JButton
• The JButton class provides the functionality of a
push button.
• JButton allows an icon, string, or both to be
associated with the push button.
• Some of its constructors are shown here:
• JButton(Icon i)
• JButton(String s)
• JButton(String s, Icon i)
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
JCheckBox
• The JCheckBox class, which provides the functionality of a
check box, is a concrete implementation of AbstractButton.
• It is immediate super-class is JToggleButton, which
provides support for two-state buttons.
• Some of its constructors are shown here:
• JCheckBox(Icon i)
• JCheckBox(Icon i, boolean state)
• JCheckBox(String s)
• JCheckBox(String s, boolean state)
• JCheckBox(String s, Icon i)
• JCheckBox(String s, Icon i, boolean state)
• The state of the check box can be changed via the
following method:
• void setSelected(boolean state)
• When a check box is selected or deselected, an item
event is generated. This is handled by
itemStateChanged( ).
• Inside itemStateChanged( ), the getItem( ) method
gets the JCheckBox object that generated the event.
• The getText( ) method gets the text for that check
box.
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Radio Buttons
• Radio buttons are supported by the JRadioButton class,
which is a concrete implementation of AbstractButton. Its
immediate super-class is JToggleButton, which provides
support for two-state buttons.
• Some of its constructors are shown here:
• JRadioButton(Icon i)
• JRadioButton(Icon i, boolean state)
• JRadioButton(String s)
• JRadioButton(String s, boolean state)
• JRadioButton(String s, Icon i)
• JRadioButton(String s, Icon i, boolean state)
• Radio buttons must be configured into a group.
Only one of the buttons in that group can be
selected at any time.
• The ButtonGroup class is instantiated to create a
button group. Its default constructor is invoked
for this purpose.
• Elements are then added to the button group via
the following method:
• void add(AbstractButton ab)
public class JRadioButtonDemo extends JApplet
implements ActionListener {
JTextField tf;
public void init() { ButtonGroup bg = new
Container contentPane = getContentPane(); ButtonGroup();
contentPane.setLayout(new FlowLayout()); bg.add(b1);
JRadioButton b1 = new JRadioButton("A"); bg.add(b2);
b1.addActionListener(this); bg.add(b3);
contentPane.add(b1); tf = new JTextField(5);
contentPane.add(tf);
JRadioButton b2 = new JRadioButton("B"); }
b2.addActionListener(this);
contentPane.add(b2); public void
actionPerformed(ActionEvent ae)
{
JRadioButton b3 = new JRadioButton("C"); tf.setText(ae.getActionCommand(
b3.addActionListener(this); ));
}
contentPane.add(b3);
}
JComboBox
• Swing provides a combo box (a combination of a text field
and a dropdown list) through the JComboBox class, which
extends JComponent.
• A combo box normally displays one entry. However, it can
also display a drop-down list that allows a user to select a
different entry. We can also type our selection into the text
field.
• Two of JComboBox’s constructors are shown here:
• JComboBox( )
• JComboBox(Vector v)
• JComboBox(Objects obj[])
• Here, v is a vector that initializes the combo box and obj is the
array of objects.
• Items are added to the list of choices via the addItem( ) method :
tree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
doMouseClicked(me);
}
});
}
void doMouseClicked(MouseEvent me)
{
TreePath p=tree.getPathForLocation(me.getX(),me.getY());
if(tp!=null)
jtf.setText(tp.toString());
else
jtf.setText("");
}
}
Tables