AOT Unit 2
AOT Unit 2
Introduction to Swing
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit
[AWT]. Java Swing offers much-improved functionality over AWT, new components, expanded
components features, and excellent event handling with drag-and-drop support.
Introduction of Java Swing
Swing has about four times the number of User Interface [UI] components as AWT and is part of
the standard Java distribution. By application GUI requirements, AWT is a limited
implementation, not quite capable of providing the components required for developing complex
GUIs required in modern commercial applications. The AWT component set has quite a few bugs
and does take up a lot of system resources when compared to equivalent Swing resources. Netscape
introduced its Internet Foundation Classes [IFC] library for use with Java. Its Classes became very
popular with programmers creating for commercial applications.
Swing is a Set of API (API- Set of Classes and Interfaces)
Swing is Provided to Design Graphical User Interfaces
Swing is an Extension library to the AWT (Abstract Window Toolkit) 5:00 5:30 pm
Includes New and improved Components that have been enhancing the looks and
Functionality of GUIs
Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and
Applets
It Employs model/view design architecture.
Swing is more portable and more flexible than AWT, the Swing is built on top of the
AWT.
Swing is Entirely written in Java.
Java Swing Components are Platform-independent, and The Swing Components are
lightweight.
Swing Supports a Pluggable look and feel and Swing provides more powerful
components.
such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
Further Swing Follows MVC.
Difference between Java Swing and Java AWT
There are certain points from which Java Swing is different than Java AWT as mentioned below:
Java AWT Java Swing
Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
applications in Java. and is used to create various applications.
Execution Time is more than Swing. Execution Time is less than AWT.
Java
// Main class
class GFG {
Output:
Example 2: Write a program to create three buttons with caption OK, SUBMIT, CANCEL.
Java
class button {
button()
{
Frame f = new Frame();
// Button 1 created
// OK button
Button b1 = new Button("OK");
b1.setBounds(100, 50, 50, 50);
f.add(b1);
// Button 2 created
// Submit button
Button b2 = new Button("SUBMIT");
b2.setBounds(100, 101, 50, 50);
f.add(b2);
// Button 3 created
// Cancel button
Button b3 = new Button("CANCEL");
b3.setBounds(100, 150, 80, 50);
f.add(b3);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}
Output:
Java
// Driver Class
class Lan {
// Main Function
Lan()
{
// Frame Created
Frame f = new Frame();
// CheckBox created
Checkbox c3 = new Checkbox("English");
c3.setBounds(100, 200, 80, 50);
f.add(c3);
// CheckBox created
Checkbox c4 = new Checkbox("marathi");
c4.setBounds(100, 250, 80, 50);
f.add(c4);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}
Output:
JApplet in Java
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The
JApplet class extends the Applet class.
1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionListener{
5. JButton b;
6. JTextField tf;
7. public void init(){
8.
9. tf=new JTextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new JButton("Click");
13. b.setBounds(80,150,70,40);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is invoked only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Java JButton
The JButton class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed. It inherits AbstractButton class.
Constructor Description
Methods Description
Output:
Java JToggleButton
Nested Classes
Constructors
Constructor Description
JToggleButton(Action a) It creates a toggle button where properties are taken from the
Action supplied.
JToggleButton(Icon icon, boolean It creates a toggle button with the specified image and
selected) selection state, but no text.
JToggleButton(String text) It creates an unselected toggle button with the specified text.
JToggleButton(String text, boolean It creates a toggle button with the specified text and selection
selected) state.
JToggleButton(String text, Icon It creates a toggle button that has the specified text and
icon) image, and that is initially unselected.
JToggleButton(String text, Icon It creates a toggle button with the specified text, image, and
icon, boolean selected) selection state.
Methods
String getUIClassID() It returns a string that specifies the name of the l&f
class that renders this component.
JToggleButton Example
1. import java.awt.FlowLayout;
2. import java.awt.event.ItemEvent;
3. import java.awt.event.ItemListener;
4. import javax.swing.JFrame;
5. import javax.swing.JToggleButton;
6.
7. public class JToggleButtonExample extends JFrame implements ItemListener {
8. public static void main(String[] args) {
9. new JToggleButtonExample();
10. }
11. private JToggleButton button;
12. JToggleButtonExample() {
13. setTitle("JToggleButton with ItemListener Example");
14. setLayout(new FlowLayout());
15. setJToggleButton();
16. setAction();
17. setSize(200, 200);
18. setVisible(true);
19. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. private void setJToggleButton() {
22. button = new JToggleButton("ON");
23. add(button);
24. }
25. private void setAction() {
26. button.addItemListener(this);
27. }
28. public void itemStateChanged(ItemEvent eve) {
29. if (button.isSelected())
30. button.setText("OFF");
31. else
32. button.setText("ON");
33. }
34. }
Output
Java JCheckBox
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
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it is
selected) initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the Action
supplied.
Methods Description
Output:
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.
Constructor Description
JRadioButton(String s, boolean Creates a radio button with the specified text and selected
selected) status.
Commonly used Methods:
Methods Description
Output:
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown
on the top of a menu. It inherits JComponent class.
Constructor Description
Methods Description
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.
Output:
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.
Constructor Description
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
Methods Description
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
Output:
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a single
line of read only text. The text can be changed by an application but a user cannot edit it directly. It
inherits JComponent class.
Constructor Description
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.
Methods Description
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X
axis.
Output:
Java JTabbedPane
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
Output:
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 pane's client. The two int parameters, when present, set the
JScrollPane(Component) vertical and horizontal scroll bar policies (respectively).
JScrollPane(int, int)
JScrollPane(Component,
int, int)
Useful Methods
void setColumnHeaderView(Component) It sets the column header for the scroll pane.
void setRowHeaderView(Component) It sets the row header for the scroll pane.
void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and must be
Component getCorner(String) one of the following constants defined in
ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
JScrollPane Example
1. import java.awt.FlowLayout;
2. import javax.swing.JFrame;
3. import javax.swing.JScrollPane;
4. import javax.swing.JtextArea;
5.
6. public class JScrollPaneExample {
7. private static final long serialVersionUID = 1L;
8.
9. private static void createAndShowGUI() {
10.
11. // Create and set up the window.
12. final JFrame frame = new JFrame("Scroll Pane Example");
13.
14. // Display the window.
15. frame.setSize(500, 500);
16. frame.setVisible(true);
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18.
19. // set flow layout for the frame
20. frame.getContentPane().setLayout(new FlowLayout());
21.
22. JTextArea textArea = new JTextArea(20, 20);
23. JScrollPane scrollableTextArea = new JScrollPane(textArea);
24.
25. scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROL
LBAR_ALWAYS);
26. scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR
_ALWAYS);
27.
28. frame.getContentPane().add(scrollableTextArea);
29. }
30. public static void main(String[] args) {
31.
32.
33. javax.swing.SwingUtilities.invokeLater(new Runnable() {
34.
35. public void run() {
36. createAndShowGUI();
37. }
38. });
39. }
40. }
Output:
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.
Constructor Description
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> Creates a JList that displays elements from the specified, non-null,
dataModel) model.
Methods Description
ListModel getModel() It is used to return the data model that holds a list
of items displayed by the JList component.
Output:
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.
Constructor Description
JTree(Object[] Creates a JTree with every element of the specified array as the child of a new
value) root node.
JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays the root
root) node.
Output:
Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.
Constructor Description
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
Output:
Introduction to JavaBeans
In simple terms, JavaBeans are classes which encapsulate several objects into a single object. It helps
in accessing these object from multiple places. JavaBeans contains several elements like Constructors,
Getter/Setter Methods and much more.
1. getEmployeeName ()
For example, if the employee name is firstName, the method name would be getFirstName() to read
that employee name. This method is known as an accessor. Properties of getter methods are as
follows:
2.setEmployeeName ()
For example, if the employee name is firstName, the method name would be setFirstName() to write
that employee name. This method is known as a mutator. Properties of setter methods:
Now that you have attained some theoretical knowledge about JavaBeans, let us move on and
understand the implementation process.
Chandler
Advantages of Javabeans
The best thing about Java beans is that you have to write code only once and can run
anywhere.
You can work on several local platforms.
The developer can control properties, methods, and events.
At design time, a user can configure JavaBeans without any disturbance.
have to make the extra effort to create a suitable environment to support JavaBean.
JavaBeans are compatible in nature.
Public T getN()
Public void setN( T arg)
package sunw.demo.indexdemo;
public class indexdemo
{
private final static int n=5;
private boolean X[];
public indexdemo()
{
x=new boolean[n];
for(int i=0;i<n;i++)
X[i]=false;
}
public boolean getX(int index)
{
return X[index];
}
public void setX(int index,boolean value)
{
X[index]=value;
}
public void setX(boolean values[])
{
X=values;
}
}