Unit V-1
Unit V-1
These provide pre-built components and tools to build functional GUI applications:
import java.awt.*;
public class BorderLayoutExample
OUTPUT
{
public static void main(String[] args)
{
Frame frame = new Frame();
frame.setLayout(new BorderLayout());
frame.add(new Button("North"), BorderLayout.NORTH);
frame.add(new Button("South"), BorderLayout.SOUTH);
frame.add(new Button("Centre"), BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
GridLayout
• Components are placed in a grid with a specified number of rows and columns.
import java.awt.*;
public class GridLayoutExample {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setLayout(new GridLayout(2, 2)); // 2 rows, 2 columns
frame.add(new Button("Button 1"));
OUTPUT
frame.add(new Button("Button 2"));
frame.add(new Button("Button 3"));
frame.add(new Button("Button 4"));
frame.setSize(300, 200);
frame.setVisible(true);
}
}
CardLayout
Displays one component at a time, often used for wizards or tabbed panels.
import java.awt.*;
public class CardLayoutExample {
public static void main(String[] args)
{
OUTPUT
Frame frame = new Frame();
CardLayout cardLayout = new CardLayout();
Panel panel = new Panel(); // Panel to hold CardLayout components
panel.setLayout(cardLayout);
panel.add(new Button("Page 1"), "Page1");
panel.add(new Button("Page 2"), "Page2");
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
cardLayout.show(panel, "Page1"); // Show "Page 1" }
}
Need of layout manager
•Automatic Layout Adjustments: The layout manager automatically adjusts the positioning and
sizing of components when the window is resized, so you don't have to manually reposition
each component.
•Separation of Concerns: It helps separate the logic of component arrangement from the
functionality of the application, making your code cleaner and more maintainable.
•Consistency: It ensures that the layout behaves consistently across different platforms and
screen sizes, preventing UI components from overlapping or looking out of place.
•Flexibility: Many layout managers provide different ways to arrange components (e.g., grid-
based, flow-based, or absolute positioning), which gives flexibility in UI design.
•Responsiveness: It’s particularly useful in creating responsive UIs that adapt to various screen
sizes without needing extra code to handle different screen resolutions or aspect ratios.
Abstract Window Toolkit(AWT)
• AWT(Abstract Window Toolkit) is a Java library used for creating GUI. It is a part of java’s
Standard library and provides a set of components like Buttons, Labels, TextField and more
for building GUI applications.
AWT Components
Container components : can hold other components
• Frame : A top-level window
• Panel: A generic container
• Dialog: A pop-up window
User interface components: used for interaction
• Button : clickable button
• Label : displays text
• TextField : Single line text input
• TextArea : Multi-line text input
• Choice : drop down menu
Layout Managers (Arrange components)
• FlowLayout: Components arranged in a row (left to right).
• BorderLayout: Divides space into 5 areas (north, south, east, west, center).
• GridLayout: Components arranged in rows and columns.
Graphics (Drawing)
•Graphics: Used for basic drawing of shapes and text.
•Graphics2D: A more advanced version of Graphics for enhanced drawing capabilities.
import java.awt.*; JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
import javax.swing.*; JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
public class Border f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
{ f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
JFrame f; f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
Border() f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
{ f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
f = new JFrame(); f.setSize(300, 300);
OUTPUT
// creating buttons
f.setVisible(true);
JButton b1 = new JButton("NORTH");;
}
// the button will be labeled as NORTH JButton b2 =
new JButton("SOUTH");; public static void main(String[] args)
// the button will be labeled as SOUTH {
JButton b3 = new JButton("EAST");; new Border();
// the button will be labeled as EAST }
}
Introduction to Menu
A user interface element that provides a list of options.
Commonly used for:
• File operations (New, Open, Save, Exit).
• Edit operations (Cut, Copy, Paste).
• View options
• Help information
Why Use Menus ?
• Improves user experience
• Organizes functionality
• Platform independence
Java swing components for Menus
• JMenuBar: Holds the main menu bar at the top of the window.
• JMenu: Represents a single menu (e.g., “File”, “Edit”, “Help”).
• JMenuItem: Represents an individual item within a menu.
Adding menu to window
import javax.swing.*; Output
public class MenuExample1
{
public static void main(String as[])
{
JFrame frame = new JFrame("Menu Example");
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem ("open");
JMenuItem saveItem = new JMenuItem ("Save");
JMenuItem exitItem= new JMenuItem ("Exit");
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(exitItem);
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Adding menu to window
Adding action listeners
• Handle user interactions:
• Implement ActionListener interface.
• Add ActionListner to each JMenuItem.
• Define the actions to perform when a menu item is clicked(e.g., open a file, save
data, exit the application).
• Output
import javax.swing.*;
import java.awt.event.*;
public class ActionListenerExample implements ActionListener
{
public static void main(String[] args) {
ActionListenerExample example = new ActionListenerExample();
example.createAndShowGUI();
}
private void createAndShowGUI(){
JFrame frame = new JFrame("ActionListener Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "Button Clicked!");
}
}
Extending GUI features Using Swing Components
• Swing has about four times the number of User Interface [UI] components as AWT and is part of the standard Java
distribution. By today’s 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 GUI’s 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)
• 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
Features Of Swing Class
• Pluggable look and feel.
• Uses MVC architecture.
• Lightweight Components
• Platform Independent
• Advanced features such as JTable, JTabbedPane, JScollPane, etc.
• Java is a platform-independent language and runs on any client machine, the GUI look and feel, owned
and delivered by a platform-specific O/S, simply does not affect an application’s GUI constructed using
Swing components.
• Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight component
development. For a component to qualify as lightweight, it must not depend on any non-Java [O/s based)
system classes. Swing components have their own view supported by Java’s look and feel classes.
• Pluggable Look and Feel: This feature enable the user to switch the look and feel of Swing components
without restarting an application. The Swing library supports components’ look and feels that remain the
same across all platforms wherever the program runs. The Swing library provides an API that gives real
flexibility in determining the look and feel of the GUI of an application
• Highly customizable – Swing controls can be customized in a very easy way as visual appearance is
independent of internal representation.
• Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane, slider, colorpicker,
and table controls.
Swing Classes Hierarchy
// Java program to create three buttons
// with caption OK, SUBMIT, CANCEL
import java.awt.*;
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);
}
A Component is the Abstract base class for about the non-menu user-interface controls of Java SWING. Components are
Component
representing an object with a graphical representation.
A JComponent is a base class for all swing UI Components In order to use a swing component that inherits from JComponent, the
JComponent
component must be in a containment hierarchy whose root is a top-level Java Swing container.
JColorChooser A JColorChooser provides a pane of controls designed to allow the user to manipulate and select a color.
JCheckBox A JCheckBox is a graphical (GUI) component that can be in either an on-(true) or off-(false) state.
JRadioButton The JRadioButton class is a graphical (GUI) component that can be in either an on-(true) or off-(false) state. in the group
JList A JList component represents the user with the scrolling list of text items.
JComboBox A JComboBox component is Presents the User with a show up Menu of choices.
JTextField A JTextField object is a text component that will allow for the editing of a single line of text.
JPasswordField
A JPasswordField object it is a text component specialized for password entry.
JTextArea A JTextArea object is a text component that allows for the editing of multiple lines of text.
Imagelcon A ImageIcon control is an implementation of the Icon interface that paints Icons from Images
JScrollbar A JScrollbar control represents a scroll bar component in order to enable users to Select from range values.
JOptionPane JOptionPane provides set of standard dialog boxes that prompt users for a value or Something.
JFileChooser A JFileChooser it Controls represents a dialog window from which the user can select a file.
JProgressBar
As the task progresses towards completion, the progress bar displays the tasks percentage on its completion.
JSlider A JSlider this class is letting the user graphically (GUI) select by using a value by sliding a knob within a bounded interval.
A JSpinner this class is a single line input where the field that lets the user select by using a number or an object value from an
JSpinner
ordered sequence.