unit 5 java
unit 5 java
Unit 5
What is swing?
In Java, Swing is a set of graphical user interface (GUI) components that are part of the Java Foundation Classes (JFC) library.
Swing provides a rich set of GUI components, including buttons, text fields, labels, menus, and more, allowing developers to
create interactive and visually appealing desktop applications in Java.
Swing is built on top of the Abstract Window Toolkit (AWT) but provides a more advanced and flexible set of components
compared to AWT. Swing components are lightweight, meaning they are not dependent on the native platform's GUI
components and have a consistent appearance across different operating systems.
Some key features of Swing include:
1. Lightweight components: Swing components are lightweight and independent of the underlying operating system's GUI
components. This allows Swing applications to have consistent behavior and appearance across different platforms.
2. Customizable look and feel: Swing allows developers to customize the look and feel of their applications using pluggable
look and feel (PLAF) mechanisms. This means that developers can choose different styles and themes for their applications.
3. Rich set of components: Swing provides a wide range of GUI components for building user interfaces, including buttons, text
fields, labels, checkboxes, radio buttons, tables, trees, and more.
4. Event-driven programming model: Swing follows an event-driven programming model, where user interactions and system
events trigger responses from the application. Developers can register event listeners to handle these events and update the
application's state accordingly.
5. Layout managers: Swing provides layout managers that help developers arrange GUI components within containers
dynamically. Layout managers handle the positioning and sizing of components based on various factors such as container size,
component preferences, and alignment constraints.
Overall, Swing has been widely used for developing desktop applications in Java due to its flexibility, portability, and extensive
set of features. However, with the introduction of JavaFX, which offers more modern features and improved performance,
Swing has seen decreasing popularity in recent years.
What are swing classes?
Swing classes in Java represent the various components and utilities provided by the Swing framework for building graphical user interfaces
(GUIs). These classes are part of the javax.swing package and its subpackages. Here are some common Swing classes:
1. JFrame: JFrame is a top-level container that represents the main window of a Swing application. It provides methods for managing the
window's appearance, such as setting its size, title, and default close operation.
2. JPanel: JPanel is a container that can hold other Swing components. It is often used to group related components together within a
window or dialog.
3. JButton: JButton is a clickable button component that triggers an action when pressed. It is commonly used to perform actions like
submitting a form or initiating a process.
4.JLabel: JLabel is a non-editable text component that displays a single line of text or an image. It is often used to provide descriptive text or
headings in a GUI.
5. JTextField: JTextField is a text input component that allows users to enter and edit text. It provides methods for getting and setting the
text value entered by the user.
6. JTextArea: JTextArea is a multiline text input component that allows users to enter and edit longer text passages. It provides scrolling
functionality for viewing and editing large amounts of text.
7. JComboBox: JComboBox is a dropdown list component that allows users to select an item from a list of options. It can be configured to
display a predefined list of items or allow users to enter custom text.
8. JCheckBox: JCheckBox is a checkbox component that allows users to toggle between two states: selected and deselected. It is commonly
used for representing binary choices or toggling options.
9. JRadioButton: JRadioButton is a radio button component that allows users to select one option from a group of mutually exclusive
options. It is often used in conjunction with other radio buttons to represent multiple-choice questions or settings.
10. Layout Managers: Layout managers such as BorderLayout, FlowLayout, GridLayout, and GroupLayout are classes used to arrange Swing
components within containers dynamically. They handle the positioning and sizing of components based on various layout constraints.
These are just a few examples of Swing classes. Swing provides a comprehensive set of classes for building GUI applications, including
support for menus, dialogs, tables, trees, and more. Developers can combine these classes to create rich and interactive user interfaces in
Java applications.
Working with Jframe windows in
java:
Thе Java JFramе is an еssеntial componеnt of Java Swing, which is a part of thе Java SWT(Standard Widgеt Toolkit). JFrame
in Java is a class that allows you to crеatе and manage a top-lеvеl window in a Java application. It sеrvеs as thе main window for
GUI-basеd Java applications and providеs a platform-indеpеndеnt way to crеatе graphical usеr intеrfacеs. In Java JFrame is a
part of javax.swing package.
Constructor of Java JFrame
Constructor Description
JFrame() This is the default constructor for JFrame. It creates a new frame with no title
JFrame(String title) This constructor creates a new frame with the specified title.
JFrame(String title, This constructor creates a JFrame with the specified title and using the
GraphicsConfiguration gc) specified graphics configuration.
JFrame(Rectangle bounds) This constructor creates a JFrame with the specified bounds.
setDefaultCloseOperation(int Sets the default close operation for the JFrame. Common options include JFrame.EXIT_ON_CLOSE,
operation) JFrame.HIDE_ON_CLOSE, and JFrame.DO_NOTHING_ON_CLOSE.
setVisible(boolean b) Sets the visibility of the JFrame. Pass true to make it visible and false to hide it.
setLayout(LayoutManager manager) Sets the layout manager for the JFrame, which controls how components are arranged within the frame.
validate() Forces the layout manager to recalculate the layout of components within the JFrame.
setResizable(boolean resizable) Controls whether the user can resize the JFrame.
setIconImage(Image image) Sets the icon (image) for the JFrame window.
Parent Classes of JFrame Methods
Java JFrame is the part of Java Swing and the classes from where all the methods associated with JFrame are inherited are
mentioned below:
1. java.awt.Frame
2. java.awt.Container
3. java.awt.Window
4. javax.swing.JFrame
Some Fields for Java JFrame
Fields Description
A field that specifies the default operation to perform when
EXIT_ON_CLOSE (int) the user closes the JFrame. It’s typically used with the
setDefaultCloseOperation() method.
HIDE_ON_CLOSE (int) Specifies that the JFrame should be hidden but not disposed
of when the user closes it.
decode(String nm) converts a String to an integer and returns the specified opaque Color.
equals(Object obj) determines whether another Color object is equal to this Color.
getAlpha() returns the alpha component in the range 0-255.
getBlue() returns the blue component in the range 0-255 .
getColor(String nm) Finds a color in the system properties.
getColor(String nm, Color v) Finds a color in the system properties.
getColor(String nm, int v) Finds a color in the system properties.
getColorComponents(ColorSpace returns a float array containing only the color components of the Color in the ColorSpace specified by the cspace parameter.
cspace, float[] compArray)
getColorComponents(float[] returns a float array containing only the color components of the Color, in the ColorSpace of the Color.
compArray)
getColorSpace() returns the ColorSpace of this Color.
getGreen() returns the green component in the range 0-255 in the default sRGB space.
getRed() returns the red component in the range 0-255 in the default sRGB space.
getRGB() Returns the RGB value representing the color in the default sRGB ColorModel.
getHSBColor(float h, float s, float Creates a Color object based on the specified values for the HSB color model.
b)
getTransparency() returns the transparency mode for this Color.
hashCode() computes the hash code for this Color.
HSBtoRGB(float h, float s, float b) Converts the HSB value to RGB value
RGBtoHSB(int r, int g, int b, converts the RGB value to HSB value
float[] hsbvals)
Adding and removing controls
Programs can be written to add different kinds of controls to your application. You can add single control or you can also add
multiple controls to your application by writing an appropriate program. Similarly, you can remove the added control with the
help of a program.
In order to include a control in a window, we must add it to the window. So, we must first create an instance of the desired
control and then add it to a window by calling add( ), which is defined by Container. The add ( ) method has several forms. The
following form is the one that is used for the first part of this
Component add(Component compObj)
Here, compObj is an instance of the control that we want to add. A reference to compObj is returned. Once a control has been
added, it will automatically be visible whenever its parent window is displayed. Sometimes we will want to remove a control
from a window when the control is no longer needed. For doing this, call remove( ). This method is also defined by Container. It
has this general form:
void remove(Component obj)
Here, obj is a reference to the control that we want to remove. We can remove all controls by calling removeAll( ).
To add a control to a collection programmatically
• Create an instance of the control to be added.
• Set properties of the new control.
• Add the control to the Controls collection of the parent control.
To remove controls from a collection programmatically
• Remove the event handler from the event
• Use the Remove method to delete the desired control from the panel’s Control collection.
Responding To Controls
Responding to controls in a Java Swing application involves adding event listeners to
the controls (such as buttons, text fields, etc.) and defining the actions to be performed
when these controls trigger events. Here's how you can respond to controls in Swing:
1. Adding Event Listeners
You need to add event listeners to the controls to handle user interactions. For
example, you can add an action listener to a button to respond to clicks, or add a
document listener to a text field to respond to text changes.
Example:
import javax.swing.*;
import java.awt.event.*;
public class MyApplication extends JFrame {
public MyApplication() {
setTitle("My Application");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a button
JButton button = new JButton("Click Me");
// Add action listener to the button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Action to perform when the button is clicked
JOptionPane.showMessageDialog(MyApplication.this, "Button Clicked!");
}
});
// Add the button to the frame
getContentPane().add(button);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new MyApplication().setVisible(true);
});
}
Output:
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, 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 CheckboxGroupExample();
}
Choice control:
Choice class is part of Java Abstract Window Toolkit(AWT). The Choice class presents a pop- up menu for the user, the user may select an item
from the popup menu. The selected item appears on the top. The Choice class inherits the Component.
Constructor for the Choice class
• Choice() : creates an new empty choice menu .
Choice Class Methods
Sr. no. Method name Description
1. void add(String item) It adds an item to the choice menu.
2. void It adds the item listener that receives item events from the choice menu.
addItemListener(ItemListe
ner l)
3. void addNotify() It creates the peer of choice.
4. AccessibleContext It gets the accessbile context related to the choice.
getAccessibleContext()
5. String getItem(int index) It gets the item (string) at the given index position in the choice menu.
6. int getItemCount() It returns the number of items of the choice menu.
7. ItemListener[] It returns an array of all item listeners registered on choice.
getItemListeners()
8. T[] Returns an array of all the objects currently registered as FooListeners upon this
getListeners(Class listenerT Choice.
ype)
9. int getSelectedIndex() Returns the index of the currently selected item.
10. String getSelectedItem() Gets a representation of the current choice as a string.
11. Object[] Returns an array (length 1) containing the currently selected item.
getSelectedObjects()
12. void insert(String item, int Inserts the item into this choice at the specified position.
index)
15. protected void Processes item events occurring on this Choice menu by dispatching them to any
processItemEvent registered ItemListener objects.
(ItemEvent e)
16. void remove(int position) It removes an item from the choice menu at the given index position.
17. void remove(String item) It removes the first occurrence of the item from choice menu.
18. void removeAll() It removes all the items from the choice menu.
19. void removeItemListener It removes the mentioned item listener. Thus is doesn't receive item events from the
(ItemListener l) choice menu anymore.
20. void select(int pos) It changes / sets the selected item in the choice menu to the item at given index
position.
21. void select(String str) It changes / sets the selected item in the choice menu to the item whose string value is
equal to string specified in the argument.
Example:
// importing awt class
import java.awt.*;
public class ChoiceExample1 {
// class constructor
ChoiceExample1() {
// creating a frame
Frame f = new Frame();
// creating a choice component
Choice c = new Choice();
// setting the bounds of choice menu
c.setBounds(100, 100, 75, 75);
// adding items to the choice menu
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
// adding choice menu to frame
f.add(c);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new ChoiceExample1();
}
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.
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> Creates a JList that displays elements from the specified,
Commonly
dataModel) used Methods:non-null, model.
Methods Description
Void It is used to add a listener to the list, to be notified each time a change to
addListSelectionListener(Li the selection occurs.
stSelectionListener
listener)
int getSelectedIndex() It is used to return the smallest selected cell index.
ListModel getModel() It is used to return the data model that holds a list of items displayed by
the JList component.
Example:
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
Jtextfeild:
JTextField is a part of javax.swing package. The class JTextField is a component that allows editing of a
single line of text. JTextField inherits the JTextComponent class and uses the interface SwingConstants.
The constructor of the class are :
1.JTextField() : constructor that creates a new TextField
2.JTextField(int columns) : constructor that creates a new empty TextField with specified number of
columns.
3.JTextField(String text) : constructor that creates a new empty text field initialized with the given
string.
4.JTextField(String text, int columns) : constructor that creates a new empty textField with the given
string and a specified number of columns .
5.JTextField(Document doc, String text, int columns) : constructor that creates a textfield that uses
the given text storage model and the given number of columns.
Methods of the JTextField are:
6.setColumns(int n) :set the number of columns of the text field.
7.setFont(Font f) : set the font of text displayed in text field.
8.addActionListener(ActionListener l) : set an ActionListener to the text field.
9.int getColumns() :get the number of columns in the textfield.
Example:
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
JtextArea:
JTextArea is a part of java Swing package . It represents a multi line area that displays text. It is used to edit
the text . JTextArea inherits JComponent class. The text in JTextArea can be set to different available fonts
and can be appended to new text . A text area can be customized to the need of user .