ssc gd
ssc gd
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built
on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java. Unlike AWT, Java Swing
provides platform-independent and lightweight components. The javax.swing package provides classes for java
swing API such as JButton, JTextField, JTextArea, JRadioButton,JCheckbox, JMenu, JColorChooser etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop
applications.
Example1:
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Example2:
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample2 {
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 SCITS, KNR.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
import javax.swing.*;
public class Simple2 extends JFrame{
JFrame f;
Simple2(){
JButton b=new JButton("click");
b.setBounds(130,100,100, 40);
add(b);
setSize(400,500);
setLayout(null);
setVisible(true);
}
Example4:
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It inherits
JTextComponent class.
Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or off.
Nested Classes
Modifier and Class Description
Type
protected class JToggleButton.AccessibleJToggleButton This class implements accessibility support for the
JToggleButton class.
static class JToggleButton.ToggleButtonModel The ToggleButton model
Constructors
Constructor Description
JToggleButton() It creates an initially unselected toggle button without setting the text or
image.
JToggleButton(Action a) It creates a toggle button where properties are taken from the Action
supplied.
JToggleButton(Icon icon) It creates an initially unselected toggle button with the specified image
but no text.
JToggleButton(Icon icon, boolean selected) It creates a toggle button with the specified image and selection state,
but no text.
JToggleButton(String text) It creates an unselected toggle button with the specified text.
JToggleButton(String text, boolean selected) It creates a toggle button with the specified text and selection state.
JToggleButton(String text, Icon icon) It creates a toggle button that has the specified text and image, and that
is initially unselected.
JToggleButton(String text, Icon icon, boolean It creates a toggle button with the specified text, image, and selection
R22-OOPTJ-Unit4 Notes - Prepared by Dr.P.KISHOR, HOD-CSE, SCITS Page 5
selected) state.
Methods
Modifier and Method Description
Type
AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with this JToggleButton.
String getUIClassID() It returns a string that specifies the name of the l&f class that renders this
component.
protected String paramString() It returns a string representation of this JToggleButton.
void updateUI() It resets the UI property to a value from the current look and feel.
JToggleButton Example
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title or icon. It
inherits JComponent class.
Constructor Description
JTabbedPane() Creates an empty TabbedPane with a default tab placement of
JTabbedPane.Top.
JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab placement.
JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab placement and tab
tabLayoutPolicy) layout policy.
Java JPasswordField
The object of a JPasswordField class is a text component specialized for password entry. It allows the editing of a single
line of text. It inherits JTextField class.
Constructor Description
Constructs a new JPasswordField, with a default document, null starting text string,
JPasswordField()
and 0 column width.
JPasswordField(int columns) Constructs a new empty JPasswordField with the specified number of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text.
JPasswordField(String text, int
Construct a new JPasswordField initialized with the specified text and columns.
columns)
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a
CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton class.
Constructor Description
JJCheckBox() Creates an initially unselected check box button with no text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it is initially
selected) selected.
JCheckBox(Action a) Creates a check box where properties are taken from the Action supplied.
Methods Description
AccessibleContext getAccessibleContext() It is used to get the AccessibleContext associated with this JCheckBox.
protected String paramString() It returns a string representation of this JCheckBox.
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from multiple options. It is
widely used in exam systems or quiz. It should be added in ButtonGroup to select one radio button only.
Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.
JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status.
Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this object.
Java JScrollBar
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation of a scrollbar. It
inherits JComponent class.
Java JList
The object of JList class represents a list of text items. The list of text items can be set up so that the user can
choose either one item or multiple items. It inherits JComponent class.
JList class declaration
public class JList extends JComponent implements Scrollable, Accessible
Commonly used Constructors:
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-null, model.
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vector.
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is editable.
void addActionListener(ActionListener a) It is used to add the ActionListener.
void addItemListener(ItemListener i) It is used to add the ItemListener.
The JMenuBar class is used to display menubar on the window or frame. It may have several menus. The object
of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits theJMenuItem
class. The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to
theJMenuItem or any of its subclass.
Java JTree
The JTree class is used to display the tree structured data or hierarchical data. JTree is a complex component. It has a 'root
node' at the top most which is a parent for all nodes in the tree. It inherits JComponent class.
The JTable class is used to display data in tabular form. It is composed of rows and columns.
Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a scroll pane to display a
large component or a component whose size can change dynamically.
Constructors
Constructor Purpose
JScrollPane() It creates a scroll pane. The Component parameter, when present, sets the scroll
JScrollPane(Component) pane's client. The two int parameters, when present, set the vertical and
JScrollPane(int, int) horizontal scroll bar policies (respectively).
JScrollPane(Component, int, int)
JScrollPane Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
public class JScrollPaneExample {
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
final JFrame frame = new JFrame("Scroll Pane Example");
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Advantages of Applet
Drawback of Applet
1. Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is
the subclass of Component.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods for an
applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for
drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet code
in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin software that resides on the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it. After
that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
c:\>javac First.java
c:\>appletviewer First.java
Java applets are loaded on a client when the user visits a page containing an applet. The security model behind
Java applets has been designed with the goal of protecting the user from malicious applets.
Applets are either sandbox applets or privileged applets. Sandbox applets are run in a security sandbox that
allows only a set of safe operations. Privileged applets can run outside the security sandbox and have extensive
capabilities to access the client.
Applets that are not signed are restricted to the security sandbox, and run only if the user accepts the applet.
Applets that are signed by a certificate from a recognized certificate authority can either run only in the sandbox,
or can request permission to run outside the sandbox. In either case, the user must accept the applet's security
certificate, otherwise the applet is blocked from running.
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Painting in Applet