Java Swing
Graphic User Interfaces Library
Introduction Main elements
● Swing is a graphic user ● Containers:
interface library.
● It extends from an older library Elements capable of containing
called AWT. other elements.
● Swing has a huge amount of ● Components:
classes.
● It is object-oriented. Elements that are added to
containers. They usually have a
graphic appearance, like buttons.
Container Types
JFrame: Used as a main JDialog: It is displayed as a JApplet: It allows to create
window with a frame and a window independent of the main applications with graphical
title bar. window to display information, interface that run in the context
such as the contents of a of a web browser.
directory.
JFrame
My First JFrame - Step by step
If you run the program, it won’t show any windows.
So, lets set the SIZE of the frame.
Now give it a try!
Still nothing? We still need to set the frame to
VISIBLE.
If you run the program now, it should show something like
this:
What happens if you close it?
The frame may close, but the execution won’t
stop.
To fix that, we need to set a default close
operation
Important JFrame Methods
● setLocation(x,y)
● setBounds(x,y,width,height)
● setIconImage(Image image)
● setTitle(String title)
● setResizable (Boolean resizable)
setLocation(x,y)
setBounds(x,y,width,height)
setResizable(Boolean resizable)
setTitle(String title)
Puts a title on the
window.
Centering the window (frame)
● Toolkit ● Width
● getScreenSize() ● Height
Centering the window
JFrame structure and JPanels
Title
Frame
Panel 1
Panel 2
Steps to add a JPanel
1. We need a JFrame
2. Create our JPanel
3. Add it to our Frame
Basic Swing Components
Basic Swing components
● JButton
● JLabel
● JTextField
● JPasswordField
Try to place a button on your Panel
setLayout(null) & setBounds(x,y,w,h)
JLabel
JTextField
JPasswordField
JCheckBox(String name, Boolean marked)
JComboBox(String[] options)
JRadioButton(String)
ButtonGroup
JSlider(min,max,current)
Sets large lines every 25.
Sets small lines every 5.
Makes the lines visible
Paints the string with
numbers
JTextArea(rows,columns) and JScrollPane(JTextArea)
Rows
Columns