Java is one of the most in-demand programming languages for developing a variety of applications. The popularity of Java can be attributed to its versatility as it can be used to design customized applications that are light and fast and serve a variety of purposes ranging from web services to android applications. Java is fast, reliable and secure. There are multiple ways to develop GUI based applications in java, out of which the most popular ones are AWT and Swing.
AWT
stands for Abstract Window Toolkit
. It is a platform-dependent API
to develop GUI (Graphical User Interface)
or window-based applications in Java. It was developed by Sun Microsystems
In 1995
. It is heavy-weight in use because it is generated by the system’s host operating system. It contains a large number of classes and methods, which are used for creating and managing GUI.
Swing
is a lightweight Java graphical user interface (GUI)
that is used to create various applications. Swing
has components which are platform-independent. It enables the user to create buttons, scroll bars and other components. Swing includes packages for creating desktop applications in Java. Swing components are written in Java language. It is a part of Java Foundation Classes(JFC)
.
AWT | Swing |
---|---|
Java AWT is an API to develop GUI applications in Java | Swing is a part of Java Foundation Classes and is used to create various applications. |
The components of Java AWT are heavy weighted. | The components of Java Swing are light weighted. |
Java AWT has comparatively less functionality as compared to Swing. | Java Swing has more functionality as compared to AWT. |
The execution time of AWT is more than Swing. | The execution time of Swing is less than AWT. |
The components of Java AWT are platform dependent. | The components of Java Swing are platform independent. |
MVC pattern is not supported by AWT. | MVC pattern is supported by Swing. |
AWT provides comparatively less powerful components. | Swing provides more powerful components. |
JFrame
is a top-level container that provides a window on the screen. A frame is actually a base window on which other components rely, namely the menu bar, panels, labels, textfields, buttons, etc. Almost every other Swing application starts with the JFrame window.
How to create a JFrame?
JFrame
class has many constructors that are used to create a new JFrame. You can create a JFrame
using these methods:
JFrame()
: This helps in creating a frame which is invisible.JFrame(String Title)
: Helps in creating a frame with a title.JFrame(GraphicsConfiguration gc)
: Creates a frame with blank title and the graphics configuration of screen.
Example:
//add the frame
JFrame jf = new JFrame("Example Frame");
//set size: width, height (in pixels)
jf.setSize(450, 475);
//set the location (x,y)
jf.setLocation(120, 60);
In Java Swing, you can display information in a custom JComponent
by creating a subclass of JComponent
and overriding its paintComponent(Graphics g)
method to customize how the information is displayed. Here's a basic example of how to do this:
CustomComponent.java:
import javax.swing.*;
import java.awt.*;
class CustomComponent extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Custom drawing code here
g.setColor(Color.BLUE);
g.setFont(new Font("Arial", Font.BOLD, 24));
g.drawString("Hello, Custom Component!", 50, 100);
}
}
Main.java:
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Custom Component Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 200);
// Create and add a custom component
CustomComponent customComponent = new CustomComponent();
frame.add(customComponent);
frame.setVisible(true);
}
}
You can draw 2D shapes on a JComponent
by overriding its paintComponent(Graphics g)
method and using the Graphics2D
object.
CustomComponent.java:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
public class CustomComponent extends JComponent {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// Set the color and stroke for the line
g2d.setColor(Color.BLUE);
g2d.setStroke(new BasicStroke(3)); // 3-pixel width
// Draw a rectangle
g2d.drawLine(500, 30, 50, 140);
// Draw a rectangle
Rectangle rect = new Rectangle(50, 50, 100, 80);
g2d.setColor(Color.BLUE);
g2d.fill(rect);
// Draw an ellipse
Ellipse2D ellipse = new Ellipse2D.Double(200, 50, 80, 100);
g2d.setColor(Color.RED);
g2d.fill(ellipse);
// Draw a custom shape
g2d.setColor(Color.GREEN);
g2d.fill(new MyShape());
// Dispose of the Graphics2D object
g2d.dispose();
}
}
class MyShape extends Path2D.Double {
public MyShape() {
moveTo(300, 50); // Move to the starting point
lineTo(50, 0); // Draw a line to (50, 0)
quadTo(50, 50, 0, 50); // Draw a quadratic curve
closePath(); // Close the path
}
}
Main.java:
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("2D Graphics Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 200);
// Create and add a custom component
CustomComponent customComponent = new CustomComponent();
frame.add(customComponent);
frame.setVisible(true);
}
}
In Java Swing, you can use colors to customize the appearance of your user interface components such as buttons, labels, panels, and backgrounds. You typically use the Color
class from the java.awt
package to work with colors.
-
Basic Colors:
Color.BLACK
: Represents the color black.Color.WHITE
: Represents the color white.Color.RED
: Represents the color red.Color.GREEN
: Represents the color green.Color.BLUE
: Represents the color blue.
-
Primary Colors:
Color.YELLOW
: Represents the color yellow.Color.CYAN
: Represents the color cyan.Color.MAGENTA
: Represents the color magenta.
-
Shades of Gray:
Color.LIGHT_GRAY
: Represents a light gray color.Color.GRAY
: Represents a medium gray color.Color.DARK_GRAY
: Represents a dark gray color.
-
System Colors:
Color.SYSTEM
: Represents the default system color (platform-dependent).
-
Transparent Colors:
Color.TRANSPARENT
: Represents a completely transparent color (fully transparent with alpha = 0).
Here's how to use colors in Swing:
You can set the background color of Swing components using the setBackground()
method. For example, to set the background color of a JPanel
to light blue:
JPanel panel = new JPanel();
panel.setBackground(Color.BLUE);
The foreground color is used for text and graphics on components like labels and buttons. You can set it using the setForeground()
method:
JLabel label = new JLabel("Hello, World!");
label.setForeground(Color.RED);
You can create custom colors using the Color
class by specifying RGB (Red, Green, Blue)
values. For example, to create a custom shade of green:
Color customGreen = new Color(0, 128, 0); // RGB values for dark green
When custom painting in Swing components (e.g., in the paintComponent(Graphics g)
method of a custom JComponent
), you can set the drawing color using Graphics2D
and setColor()
.
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.YELLOW);
// Perform custom drawing operations using the selected color
}
In Java Swing, you can use custom or special fonts for text by following these steps:
To use a special or custom font, you first need to load the font into your application. You can do this using the Font
class and the Font.createFont()
method. Here's an example of how to load a custom font from a file:
// Load the custom font from a file
try {
Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("customfont.ttf"));
} catch (IOException | FontFormatException e) {
e.printStackTrace();
}
Once you've loaded the custom font, you can derive a new Font
instance with custom attributes such as size and style. For example, to create a 20-point bold version of the custom font:
Font customFontBold = customFont.deriveFont(Font.BOLD, 20);
To apply the custom font to Swing components, you can use the setFont()
method. Here's an example of how to set the custom font for a JLabel
:
JLabel label = new JLabel("Hello, World!");
label.setFont(customFontBold); // Set the custom font
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Image Display Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Load an image.
ImageIcon imageIcon = new ImageIcon("image.png");
// Create a JLabel and set the image icon.
JLabel imageLabel = new JLabel(imageIcon);
// Add the label to the frame.
frame.getContentPane().add(imageLabel);
frame.pack();
frame.setVisible(true);
}
}
Event handling in Swing
refers to the process of detecting and responding to user actions, such as clicking a button, typing in a text field, or moving the mouse, within a Swing graphical user interface (GUI) application. Swing provides a rich framework for event handling that allows you to create interactive and responsive applications.
Swing components such as buttons, checkboxes, text fields, and others are known as event sources. These components can generate events when a user interacts with them, such as clicking a button or typing in a text field.
Event Listeners are objects that listen for specific types of events generated by event sources. Each type of event in Swing
has a corresponding listener interface. Some common event listener interfaces include:
ActionListener
: Listens for action events (e.g., button clicks).MouseListener
: Listens for mouse events (e.g., mouse clicks, movements).KeyListener
: Listens for keyboard events (e.g., key presses).FocusListener
: Listens for focus events (e.g., component gaining or losing focus).
To handle events, you need to register event listeners with the event source. You do this using methods like addActionListener
, addMouseListener
, addKeyListener
, or other similar methods provided by the component.
For example, to handle a button click event:
JButton button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Code to handle the button click event
}
});
For each listener interface, you need to implement specific event handling methods. For instance, for an ActionListener
, you implement the actionPerformed
method to specify what should happen when the event occurs. Here's a simplified example:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
Event Classes | Listener Interfaces |
---|---|
ActionEvent | ActionListener |
MouseEvent | MouseListener and MouseMotionListener |
MouseWheelEvent | MouseWheelListener |
KeyEvent | KeyListener |
ItemEvent | ItemListener |
TextEvent | TextListener |
AdjustmentEvent | AdjustmentListener |
WindowEvent | WindowListener |
ComponentEvent | ComponentListener |
ContainerEvent | ContainerListener |
FocusEvent | FocusListener |
The Adapter class provides the default modification of all methods of an interface; we don't need to modify all the methods of the interface so we can say it reduces coding burden. Sometimes or often we need a few methods of an interface. For that, the Adapter class is very helpful since it already modifies all the methods of an interface and by implementing the Adapter class, we only need to modify the required methods.
The following examples contain the following Adapter classes:
ContainerAdapter
KeyAdapter
FocusAdapter
WindowAdapter
MouseAdapter
ComponentAdapter
MouseMotionAdapter
Advantages of the Adapter Class:
- Assists unrelated classes to work together.
- Provides a way to use classes in multiple ways.
- Increases the transparency of classes.
- Its provides a way to include related patterns in a class.
- It provides a pluggable kit for developing applications.
- It makes a class highly reusable.
Swing, the GUI (Graphical User Interface) toolkit for Java, is often used in conjunction with the Model-View-Controller (MVC)
design pattern to create well-structured and maintainable GUI applications.
The Model-View-Controller (MVC)
design pattern is a widely used architectural pattern in software engineering.The Model View Controller (MVC)
design pattern specifies that an application consist of a data model, presentation information, and control information. It separates an application into three interconnected components: Model
, View
, and Controller
.
-
Model
: Model is the application's dynamic data structure, independent of the user interface. It directly manages the data, logic and rules of the application. -
View
: Any representation of information such as a chart, diagram or table. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants. -
Controller
: Accepts input and converts it to commands for theModel
orView
.
In addition to dividing the application into these components, the Model-View-Controller (MVC)
design defines the interactions between them.
- The
Model
is responsible for managing the data of the application. It receives user input from theController
. - The
View
renders presentation of the model in a particular format. - The
Controller
responds to the user input and performs interactions on the data model objects. TheController
receives the input, optionally validates it and then passes the input to the model.
CalculatorModel.java:
public class CalculatorModel {
private int num1;
private int num2;
private int result;
public void setNumbers(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public void add() {
result = num1 + num2;
}
public void subtract() {
result = num1 - num2;
}
public void multiply() {
result = num1 * num2;
}
public void divide() {
result = num1 / num2;
}
public int getResult() {
return result;
}
}
CalculatorView.java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class CalculatorView {
private JFrame frame;
private JTextField textField1, textField2;
private JButton addButton, subtractButton, multiplyButton, divideButton;
private JLabel resultLabel;
public CalculatorView() {
frame = new JFrame("Simple Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
textField1 = new JTextField(10);
textField2 = new JTextField(10);
addButton = new JButton("Add");
subtractButton = new JButton("Subtract");
multiplyButton = new JButton("Multiply");
divideButton = new JButton("Divide");
resultLabel = new JLabel("Result: ");
frame.add(textField1);
frame.add(textField2);
frame.add(addButton);
frame.add(subtractButton);
frame.add(multiplyButton);
frame.add(divideButton);
frame.add(resultLabel);
frame.pack();
frame.setVisible(true);
}
public int getNum1() {
return Integer.parseInt(textField1.getText());
}
public int getNum2() {
return Integer.parseInt(textField2.getText());
}
public void setResult(int result) {
resultLabel.setText("Result: " + result);
}
public void addCalculationListener(ActionListener listener) {
addButton.addActionListener(listener);
}
public void subtractCalculationListener(ActionListener listener) {
subtractButton.addActionListener(listener);
}
public void multiplyCalculationListener(ActionListener listener) {
multiplyButton.addActionListener(listener);
}
public void divideCalculationListener(ActionListener listener) {
divideButton.addActionListener(listener);
}
}
CalculatorController.java:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorController {
private CalculatorModel model;
private CalculatorView view;
public CalculatorController(CalculatorModel model, CalculatorView view) {
this.model = model;
this.view = view;
view.addCalculationListener(new AddListener());
view.subtractCalculationListener(new SubtractListener());
view.multiplyCalculationListener(new MultiplyListener());
view.divideCalculationListener(new DivideListener());
}
class AddListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int num1 = view.getNum1();
int num2 = view.getNum2();
model.setNumbers(num1, num2);
model.add();
view.setResult(model.getResult());
}
}
class SubtractListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int num1 = view.getNum1();
int num2 = view.getNum2();
model.setNumbers(num1, num2);
model.subtract();
view.setResult(model.getResult());
}
}
class MultiplyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int num1 = view.getNum1();
int num2 = view.getNum2();
model.setNumbers(num1, num2);
model.multiply();
view.setResult(model.getResult());
}
}
class DivideListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int num1 = view.getNum1();
int num2 = view.getNum2();
model.setNumbers(num1, num2);
model.divide();
view.setResult(model.getResult());
}
}
}
Main.java:
public class Main {
public static void main(String[] args) {
CalculatorModel model = new CalculatorModel();
CalculatorView view = new CalculatorView();
new CalculatorController(model, view);
}
}
The LayoutManagers are used to arrange components in a particular manner. The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI forms. LayoutManager is an interface that is implemented by all the classes of layout managers. There are the following classes that represent the layout managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout
javax.swing.SpringLayout
etc.
FlowLayout is used to arrange components in a sequence one after the other. The default layout of applet and panel is FlowLayout.
Fields of FlowLayout class:
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING
Constructors :
FlowLayout()
: It will Construct a new FlowLayout with centered alignment.The horizontal and vertical gap will be 5 pixels.FlowLayout(int align)
: It will Construct a new FlowLayout with given alignment.The horizontal and vertical gap will be 5 pixels.FlowLayout(int align, int HorizontalGap, int VerticalGap)
: It will Construct a new FlowLayout with given alignment, the given horizontal and vertical gap between the components.
We can control the alignment of components in a flow layout arrangement, by using these FlowLayout Fields.
RIGHT :- Each row of component shifts towards right.
JFrame jf = new JFrame("FlowLayout");
jf.setLayout(new FlowLayout(FlowLayout.RIGHT));
LEFT:- Each row of component shifts towards left.
JFrame jf = new JFrame("FlowLayout");
jf.setLayout(new FlowLayout(FlowLayout.LEFT));
Example:
import java.awt.*;
import javax.swing.*;
public class flowlayout {
public static void main(String[] args) {
JFrame jf = new JFrame("FlowLayout");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
jf.add(b1);
jf.add(b2);
jf.add(b3);
jf.add(b4);
jf.add(b5);
jf.add(b6);
jf.add(b7);
jf.add(b8);
jf.add(b9);
jf.add(b10);
jf.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 25));
jf.setSize(300, 300);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
The BorderLayout is used to arrange the components in five regions: north, south, east, west, and center. Each region (area) may contain one component only. It is the default layout of a frame or window. The BorderLayout provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
Constructors of BorderLayout class:
BorderLayout()
: creates a border layout but with no gaps between the components.BorderLayout(int HorizontalGap, int VerticalGap)
: creates a border layout with the given horizontal and vertical gaps between the components.
Example:
import javax.swing.*;
import java.awt.*;
public class borderlayout {
public static void main(String[] args) {
JFrame jf = new JFrame("BorderLayout");
JButton b1 = new JButton("NORTH");
JButton b2 = new JButton("SOUTH");
JButton b3 = new JButton("EAST");
JButton b4 = new JButton("WEST");
JButton b5 = new JButton("CENTER");
jf.setLayout(new BorderLayout(20, 15));
jf.add(b1, BorderLayout.NORTH);
jf.add(b2, BorderLayout.SOUTH);
jf.add(b3, BorderLayout.EAST);
jf.add(b4, BorderLayout.WEST);
jf.add(b5, BorderLayout.CENTER);
jf.setSize(300, 300);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
The Java GridLayout class is used to arrange the components in a rectangular grid. One component is displayed in each rectangle.
Constructors of GridLayout class:
GridLayout()
: creates a grid layout with one column per component in a row.GridLayout(int rows, int columns)
: creates a grid layout with the given rows and columns but no gaps between the components.GridLayout(int rows, int columns, int hgap, int vgap)
: creates a grid layout with the given rows and columns along with given horizontal and vertical gaps.
Example:
import javax.swing.*;
import java.awt.*;
public class gridlayout {
public static void main(String[] args) {
JFrame jf = new JFrame("GridLayout");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
jf.add(b1);
jf.add(b2);
jf.add(b3);
jf.add(b4);
jf.add(b5);
jf.add(b6);
jf.add(b7);
jf.add(b8);
jf.add(b9);
jf.add(b10);
jf.setLayout(new GridLayout(5,2,5,5));
jf.setSize(300, 300);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Swing components are the basic building blocks of an application. We know that Swing is a GUI widget toolkit for Java. Every application has some basic interactive interface for the user. For example, a button, check-box, radio-button, text-field, etc.
Below are the different components of swing in java:
The ImageIcon component creates an icon sized-image from an image residing at the source URL.
Example:
ImageIcon homeIcon = new ImageIcon("src/images/home.jpg");
This returns an icon of a home button. The string parameter is the path at which the source image is present.
JButton class is used to create a push-button on the UI. The button can contain some display text or image. It generates an event when clicked and double-clicked. A JButton can be implemented in the application by calling one of its constructors.
Example:
JButton okBtn = new JButton("Ok");
This constructor returns a button with text Ok on it.
JButton homeBtn = new JButton(homeIcon);
It returns a button with a homeIcon on it.
JButton btn2 = new JButton(homeIcon, "Home");
It returns a button with the home icon and text Home.
JLabel class is used to render a read-only text label or images on the UI. It does not generate any event.
Example:
JLabel textLbl = new JLabel("This is a text label.");
This constructor returns a label with text.
JLabel imgLabel = new JLabel(homeIcon);
It returns a label with a home icon.
JTextField renders an editable single-line text box. A user can input non-formatted text in the box. To initialize the text field, call its constructor and pass an optional integer parameter to it. This parameter sets the width of the box measured by the number of columns. It does not limit the number of characters that can be input in the box.
Example:
JTextField txtBox = new JTextField(20);
It renders a text box of 20 column width.
JTextArea class renders a multi-line text box. Similar to the JTextField, a user can input non-formatted text in the field. The constructor for JTextArea also expects two integer parameters which define the height and width of the text-area in columns. It does not restrict the number of characters that the user can input in the text-area.
Example:
JTextArea txtArea = new JTextArea("This text is default text for text area.", 5, 20);
The above code renders a multi-line text-area of height 5 rows and width 20 columns, with default text initialized in the text-area.
JPasswordField is a subclass of JTextField class. It renders a text-box that masks the user input text with bullet points. This is used for inserting passwords into the application.
Example:
JPasswordField pwdField = new JPasswordField(15);
var pwdValue = pwdField.getPassword();
It returns a password field of 15 column width. The getPassword
method gets the value entered by the user.
JCheckBox renders a check-box with a label. The check-box has two states – on/off. When selected, the state is on and a small tick is displayed in the box.
Example:
CheckBox chkBox = new JCheckBox("Show Help", true);
It returns a checkbox with the label Show Help. Notice the second parameter in the constructor. It is a boolean value that indicates the default state of the check-box. True means the check-box is defaulted to on state.
JRadioButton is used to render a group of radio buttons in the UI. A user can select one choice from the group.
Example:
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton("Easy", true);
JRadioButton rb2 = new JRadioButton("Medium");
JRadioButton rb3 = new JRadioButton("Hard");
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);
The above code creates a button group and three radio button elements. All three elements are then added to the group. This ensures that only one option out of the available options in the group can be selected at a time. The default selected option is set to Easy.
JList component renders a scrollable list of elements. A user can select a value or multiple values from the list. This select behavior is defined in the code by the developer.
Example:
DefaultListItem cityList = new DefaultListItem();
cityList.addElement("Mumbai"):
cityList.addElement("London"):
cityList.addElement("New York"):
cityList.addElement("Sydney"):
cityList.addElement("Tokyo"):
JList cities = new JList(cityList);
cities.setSelectionModel(ListSelectionModel.SINGLE_SELECTION);
The above code renders a list of cities with 5 items in the list. The selection restriction is set to SINGLE_SELECTION
. If multiple selections is to be allowed, set the behavior to MULTIPLE_INTERVAL_SELECTION.
JComboBox class is used to render a dropdown of the list of options.
Example:
String[] cityStrings = { "Mumbai", "London", "New York", "Sydney", "Tokyo" };
JComboBox cities = new JComboBox(cityList);
cities.setSelectedIndex(3);
The default selected option can be specified through the setSelectedIndex method. The above code sets Sydney as the default selected option.
JFileChooser class renders a file selection utility. This component lets a user select a file from the local system.
Example:
JFileChooser fileChooser = new JFileChooser();
JButton fileDialogBtn = new JButton("Select File");
fileDialogBtn.AddEventListner(new ActionListner(){
fileChooser.showOpenDialog();
})
var selectedFile = fileChooser.getSelectedFile();
The above code creates a file chooser dialog and attaches it to the button. The button click would open the file chooser dialog. The selected file is returned through the getSelectedFile method.
JTabbedPane is another very useful component that lets the user switch between tabs in an application. This is a highly useful utility as it lets the user browse more content without navigating to different pages.
Example:
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", new JPanel());
tabbedPane.addTab("Tab 2", new JPanel());
The above code creates a two tabbed panel with headings Tab 1 and Tab 2.
JSlider component displays a slider which the user can drag to change its value. The constructor takes three arguments – minimum value, maximum value, and initial value.
Example:
JSlider volumeSlider = new JSlider(0, 100, 50);
var volumeLevel = volumeSlider.getValue();
The above code creates a slider from 0 to 100 with an initial value set to 50. The value selected by the user is returned by the getValue method.
JPanel, a part of the Java Swing package, is a container that can store a group of components. The main task of JPanel is to organize components, various layouts can be set in JPanel which provide better organization of components, however, it does not have a title bar.
Constructors of JPanel
JPanel()
: creates a new panel with a flow layoutJPanel(LayoutManager l)
: creates a new JPanel with specified layoutManagerJPanel(boolean isDoubleBuffered)
: creates a new JPanel with a specified buffering strategyJPanel(LayoutManager l, boolean isDoubleBuffered)
: creates a new JPanel with specified layoutManager and a specified buffering strategy
Syntax:
JFrame jf = new JFrame();
JPanel jp = new JPanel();
jf.add(jp);
Example:
import javax.swing.*;
import java.awt.*;
public class Jpanel {
public static void main(String[] args) {
JFrame jf = new JFrame("Jpanel Example");
JPanel jp = new JPanel();
jp.setBounds(40,80,200,200);
jp.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
jp.add(b1);
jp.add(b2);
jf.add(jp);
jf.setLayout(null);
jf.setSize(400, 400);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
The Checkbox 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
.
Methods to add Item Listener to checkbox:
addActionListener(ItemListener l)
: adds item listener to the componentitemStateChanged(ItemEvent e)
: abstract function invoked when the state of the item to which listener is applied changesgetItem()
: Returns the component-specific object associated with the item whose state changedgetStateChange()
: Returns the new state of the item. The ItemEvent class defines two states:SELECTED
andDESELECTED
.getSource()
: Returns the component that fired the item event.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JCheckBoxEvent {
public static void main(String[] args) {
JFrame jf = new JFrame("JCheckBoxEvent");
JLabel jl = new JLabel();
jl.setBounds(100, 20, 400, 100);
Checkbox cb1 = new Checkbox("C++");
cb1.setBounds(100, 100, 50, 50);
Checkbox cb2 = new Checkbox("Java");
cb2.setBounds(100, 150, 50, 50);
jf.add(jl);
jf.add(cb1);
jf.add(cb2);
cb1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == 1) {
jl.setText("C++ Checkbox : Checked");
} else {
jl.setText("C++ Checkbox : Unchecked");
}
}
});
cb2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == 1) {
jl.setText("Java Checkbox : Checked");
} else {
jl.setText("Java Checkbox : Unchecked");
}
}
});
jf.setLayout(null);
jf.setSize(400, 400);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
We use the JRadioButton class to create a radio button. Radio button is use to select one option from multiple options. It is used in filling forms, online objective papers and quiz.
We add radio buttons in a ButtonGroup so that we can select only one radio button at a time. We use “ButtonGroup” class to create a ButtonGroup and add radio button in a group.
Example
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JComboBoxEvent {
public static void main(String[] args) {
JFrame jf = new JFrame("JComboBoxEvent");
JRadioButton rb1 = new JRadioButton("Male");
rb1.setBounds(100, 50, 100, 30);
JRadioButton rb2 = new JRadioButton("Female");
rb2.setBounds(100, 100, 100, 30);
ButtonGroup bg = new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
JButton jb = new JButton("click");
jf.add(rb1);
jf.add(rb2);
jf.add(jb);
jb.setBounds(100, 150, 80, 30);
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (rb1.isSelected()) {
JOptionPane.showMessageDialog(null, "You are Male.");
} else if (rb2.isSelected()) {
JOptionPane.showMessageDialog(null, "You are Female.");
} else {
JOptionPane.showMessageDialog(null, "You have selected nothing.Please select one.");
}
}
});
jf.setLayout(null);
jf.setSize(400, 400);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
JComboBox is a part of Java Swing package. JComboBox inherits JComponent class . JComboBox shows a popup menu that shows a list and the user can select a option from that specified list . JComboBox can be editable or read- only depending on the choice of the programmer.
Example:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JComboBoxEvent {
public static void main(String[] args) {
JFrame jf = new JFrame("JComboBoxEvent");
String languages[]={"C","C++","C#","Java","PHP","Python"};
JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
JButton jb=new JButton("Show");
jb.setBounds(200,100,75,20);
jf.add(jb);
jf.add(cb);
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "+ cb.getItemAt(cb.getSelectedIndex());
JOptionPane.showMessageDialog(null, data);
}
});
jf.setLayout(null);
jf.setSize(400, 250);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
JList is part of Java Swing package . JList is a component that displays a set of Objects and allows the user to select one or more items . JList inherits JComponent class. JList is a easy way to display an array of Vectors .
Methods:
void addListSelectionListener(ListSelectionListener listener)
:It is used to add a listener to the list, to be notified each time a change to the selection occurs.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.void setListData(Object[] listData)
:It is used to create a read-only ListModel from an array of objects.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JListEvent {
public static void main(String[] args) {
String month[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
String date[] = new String[31], year[] = new String[31];
for (int i = 0; i < 31; i++) {
date[i] = "" + (int) (i + 1);
year[i] = "" + (int) (2018 - i);
}
JFrame jf = new JFrame("JListEvent");
JLabel jl = new JLabel("Select Your Birthday:");
JList jlt1 = new JList(date);
JList jlt2 = new JList(month);
JList jlt3 = new JList(year);
jlt1.setSelectedIndex(2);
jlt2.setSelectedIndex(1);
jlt3.setSelectedIndex(2);
JButton jb = new JButton("Click");
jf.add(jl);
jf.add(jlt1);
jf.add(jlt2);
jf.add(jlt3);
jf.add(jb);
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String date = jlt1.getSelectedValue() + " " + jlt2.getSelectedValue() + " " + jlt3.getSelectedValue();
JOptionPane.showMessageDialog(null, "Your Birthday : " + date);
}
});
jf.setLayout(new FlowLayout(FlowLayout.LEFT));
jf.setVisible(true);
jf.setSize(500, 600);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Key events indicate when the user is typing at the keyboard. Specifically, key events are fired by the component with the keyboard focus when the user presses or releases keyboard keys.
KeyListener Interface This interface defines methods to respond to events arising when a key on the keyboard is pressed or released.
The KeyListener interface has three member methods :
public void keyReleased(KeyEvent)
: This method gives the Unicode of the key released and its character equivalent if the key pressed is a letter.public void keyPressed(KeyEvent)
: This method gives the Unicode of the key pressed and its character equivalent if the key pressed is a letter.public void keyTyped(KeyEvent)
: This method gives the character equivalent of the key pressed provided it is a valid character.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyEvent implements KeyListener, ActionListener {
JFrame jf;
JTextField jt;
JLabel jl;
JButton jb;
public KeyEvent() {
jf = new JFrame("Key Event");
jl = new JLabel();
jt = new JTextField(15);
jt.addKeyListener(this);
jb = new JButton("Clear");
jb.addActionListener(this);
JPanel jp = new JPanel();
jp.add(jt);
jp.add(jb);
jf.setLayout(new BorderLayout());
jf.add(jl, BorderLayout.NORTH);
jf.add(jp, BorderLayout.SOUTH);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300, 100);
jf.setVisible(true);
}
@Override
public void keyTyped(java.awt.event.KeyEvent e) {
jl.setText("You have typed " + e.getKeyChar());
System.out.println("You have typed " + e.getKeyChar());
}
@Override
public void keyPressed(java.awt.event.KeyEvent e) {
jl.setText("You have pressed " + e.getKeyChar());
System.out.println("You have pressed " + e.getKeyChar());
}
@Override
public void keyReleased(java.awt.event.KeyEvent e) {
jl.setText("You have released " + e.getKeyChar());
System.out.println("You have released " + e.getKeyChar());
}
@Override
public void actionPerformed(ActionEvent ae) {
jl.setText("");
}
public static void main(String[] args) {
new KeyEvent();
}
}
MouseListener and MouseMotionListener is an interface in java.awt.event
package. Mouse events are of two types. MouseListener handles the events when the mouse is not in motion. While MouseMotionListener handles the events when mouse is in motion.
MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.
The signature of 5 methods found in MouseListener interface are given below:
public abstract void mouseClicked(MouseEvent e);
public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);
Example:
import javax.swing.*;
import java.awt.event.*;
public class MouseListEvent implements MouseListener {
JFrame jf;
JLabel jl;
MouseListEvent() {
jf = new JFrame("MouseListEvent");
jf.addMouseListener(this);
jl = new JLabel();
jl.setBounds(20, 50, 100, 20);
jf.add(jl);
jf.setLayout(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300, 300);
jf.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
jl.setText("Mouse Clicked");
System.out.println("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
jl.setText("Mouse Entered");
System.out.println("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
jl.setText("Mouse Exited");
System.out.println("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
jl.setText("Mouse Pressed");
System.out.println("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
jl.setText("Mouse Released");
System.out.println("Mouse Released");
}
public static void main(String [] args) {
new MouseListEvent();
}
}
MouseMotionListener Interface
The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified against MouseEvent. The MouseMotionListener interface is found in java.awt.event
package. It has two methods.
Methods of MouseMotionListener interface The signature of 2 methods found in MouseMotionListener interface are given below:
public abstract void mouseDragged(MouseEvent e);
public abstract void mouseMoved(MouseEvent e);
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseMotList implements MouseMotionListener {
JFrame jf;
JLabel jl;
MouseMotList() {
jf = new JFrame("MouseMotList");
jf.addMouseMotionListener(this);
jl = new JLabel();
jf.add(jl);
jl.setBounds(20, 50, 100, 20);
jf.setSize(300, 300);
jf.setLayout(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
public void mouseDragged(MouseEvent e) {
jl.setText("Mouse Dragged");
System.out.println("Mouse Dragged");
}
public void mouseMoved(MouseEvent e) {
jl.setText("Mouse Moved");
System.out.println("Mouse Moved");
}
public static void main(String[] args) {
new MouseMotList();
}
}
JMenuBar
, JMenu
and JMenuItems
are a part of Java Swing package. JMenuBar
is an implementation of menu bar . the JMenuBar
contains one or more JMenu objects, when the JMenu
objects are selected they display a popup showing one or more JMenuItems .
JMenu
basically represents a menu . It contains several JMenuItem
Object . It may also contain JMenu
Objects (or submenu).
Constructors:
JMenuBar()
:Creates a new MenuBar.JMenu()
:Creates a new Menu with no text.JMenu(String name)
:Creates a new Menu with a specified name.JMenu(String name, boolean b)
:Creates a new Menu with a specified name and boolean value specifies it as a tear-off menu or not. A tear-off menu can be opened and dragged away from its parent menu bar or menu.
Commonly used methods:
add(JMenu c)
:Adds menu to the menu bar. Adds JMenu object to the Menu bar.add(Component c)
:Add component to the end of JMenu.add(Component c, int index)
:Add component to the specified index of JMenu.add(JMenuItem menuItem)
:Adds menu item to the end of the menu.add(String s)
:Creates a menu item with specified string and appends it to the end of menu.getItem(int index)
:Returns the specified menuitem at the given index.
Example:
import javax.swing.*;
import java.awt.event.*;
public class menu implements ActionListener {
JFrame jf;
JLabel jl;
JMenuBar mb;
JMenu x, x1;
JMenuItem m1, m2, m3, s1, s2;
menu()
{
jf = new JFrame("Menu demo");
jl = new JLabel("no task ");
jl.setBounds(200,200,300,300);
mb = new JMenuBar();
x = new JMenu("Menu");
x1 = new JMenu("submenu");
m1 = new JMenuItem("MenuItem1");
m2 = new JMenuItem("MenuItem2");
m3 = new JMenuItem("MenuItem3");
s1 = new JMenuItem("SubMenuItem1");
s2 = new JMenuItem("SubMenuItem2");
m1.addActionListener(this);
m2.addActionListener(this);
m3.addActionListener(this);
s1.addActionListener(this);
s2.addActionListener(this);
x.add(m1);
x.add(m2);
x.add(m3);
x1.add(s1);
x1.add(s2);
x.add(x1);
mb.add(x);
jf.setJMenuBar(mb);
jf.add(jl);
jf.setSize(500, 500);
jf.setLayout(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
jl.setText(s + " selected");
}
public static void main(String [] args)
{
new menu();
}
}
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 .
Constructors of JTextArea are:
JTextArea()
:constructs a new blank text area .JTextArea(String s)
:constructs a new text area with a given initial text.JTextArea(int row, int column)
:constructs a new text area with a given number of rows and columns.JTextArea(String s, int row, int column)
:constructs a new text area with a given number of rows and columns and a given initial text.
Commonly used methods:
append(String s)
:appends the given string to the text of the text area.getLineCount()
:get number of lines in the text of text area.setFont(Font f)
:sets the font of text area to the given font.setColumns(int c)
:sets the number of columns of the text area to given integer.setRows(int r)
:sets the number of rows of the text area to given integer.getColumns()
:get the number of columns of text area.getRows()
:get the number of rows of text area.
Example:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JTextAreaEx implements ActionListener {
JFrame jf;
JButton jb, jb1, jb2, jb3;
JLabel jl, jl1;
JTextArea jt;
JTextAreaEx() {
jf = new JFrame("JTextAreaEx");
jl = new JLabel("Nothing Entered");
jl1 = new JLabel("0 Lines");
jb = new JButton("Submit");
jb1 = new JButton("Plain");
jb2 = new JButton("Italic");
jb3 = new JButton("Bold");
jb.addActionListener(this);
jb1.addActionListener(this);
jb2.addActionListener(this);
jb3.addActionListener(this);
jt = new JTextArea("Please Write Something ", 10, 10);
JPanel jp = new JPanel();
jp.add(jt);
jp.add(jb);
jp.add(jb1);
jp.add(jb2);
jp.add(jb3);
jp.add(jl);
jp.add(jl1);
jf.add(jp);
jf.setSize(1000, 500);
jf.setLayout(new FlowLayout(FlowLayout.LEFT));
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("Submit")) {
jl.setText(jt.getText() + ", ");
jl1.setText(jt.getLineCount() + " lines");
} else if (s.equals("Bold")) {
Font f = new Font("Serif", Font.BOLD, 15);
jt.setFont(f);
} else if (s.equals("Italic")) {
Font f = new Font("Serif", Font.ITALIC, 15);
jt.setFont(f);
} else if (s.equals("Plain")) {
Font f = new Font("Serif", Font.PLAIN, 15);
jt.setFont(f);
}
}
public static void main(String[] args) {
new JTextAreaEx();
}
}
The JDialog control represents a top level window with a border and a title used to take some form of input from the user. It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
Commonly used Constructors:
JDialog()
:It is used to create a modeless dialog without a title and without a specified Frame owner.JDialog(Frame owner)
:It is used to create a modeless dialog with specified Frame as its owner and an empty title.JDialog(Frame owner, String title, boolean modal)
:It is used to create a dialog with the specified title, owner Frame and modality.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
public static void main(String [] args)
{
JDialog d = new JDialog((Dialog) null, "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
d.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
}
The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and input dialog box. These dialog boxes are used to display information or get input from the user. The JOptionPane class inherits JComponent class.
Common Constructors of JOptionPane class
JOptionPane()
:It is used to create a JOptionPane with a test message.JOptionPane(Object message)
:It is used to create an instance of JOptionPane to display a message.JOptionPane(Object message, int messageType)
:It is used to create an instance of JOptionPane to display a message with specified message type and default options.
Common Methods of JOptionPane class
JDialog createDialog(String title)
: It is used to create and return a new parentless JDialog with the specified title.static void showMessageDialog(Component parentComponent, Object message)
:It is used to create an information-message dialog titled "Message".static void showMessageDialog(Component parentComponent, Object message, String title, int messageType)
:It is used to create a message dialog with given title and messageType.static int showConfirmDialog(Component parentComponent, Object message)
:It is used to create a dialog with the options Yes, No and Cancel; with the title, Select an Option.static String showInputDialog(Component parentComponent, Object message)
:It is used to show a question-message dialog requesting input from the user parented to parentComponent.void setInputValue(Object newValue)
:It is used to set the input value that was selected or input by the user.
Example:
import javax.swing.*;
class JOptionP{
public static void main(String[] args) {
String name = JOptionPane.showInputDialog(null, "Enter Name:", "Question", JOptionPane.QUESTION_MESSAGE);
int n = JOptionPane.showConfirmDialog(null, "Are you Single ?");
if (n == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, name + " is Single.", "Message", JOptionPane.PLAIN_MESSAGE);
} else if (n == JOptionPane.NO_OPTION) {
JOptionPane.showMessageDialog(null, name + " is not Single.", "Message", JOptionPane.PLAIN_MESSAGE);
} else if (n == JOptionPane.CANCEL_OPTION) {
JOptionPane.showMessageDialog(null, name + " is Looser.", "Message", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, name + " you Exited", "Message", JOptionPane.WARNING_MESSAGE);
}
}
}
The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet. This arranges data in a tabular form.
Constructors in JTable:
JTable()
: A table is created with empty cells.JTable(int rows, int cols)
: Creates a table of size rows * cols.JTable(Object[][] data, Object []Column)
: A table is created with the specified name where []Column defines the column names.
Functions in JTable:
addColumn(TableColumn []column)
:adds a column at the end of the JTable.clearSelection()
:Selects all the selected rows and columns.editCellAt(int row, int col)
:edits the intersecting cell of the column number col and row number row programmatically, if the given indices are valid and the corresponding cell is editable.setValueAt(Object value, int row, int col)
:Sets the cell value as ‘value’ for the position row, col in the JTable.
Example:
import javax.swing.*;
public class JTableExample {
JFrame jf;
JTable jt;
JTableExample()
{
jf = new JFrame();
jf.setTitle("JTable Example");
String[][] data = {
{ "Prashant Bhandari","32","Birtamode" },
{ "Ram Dahal", "60", "Budhabarey" },
{ "Krishna Acharya", "66", "Bahaundagi" },
{ "Pooja Dahal", "6", "Kathmandu" },
{ "Prem Rai", "9", "Biratnagar" }
};
String[] columnNames = { "Name", "Roll Number", "Address" };
jt = new JTable(data, columnNames);
jt.setBounds(30, 40, 200, 300);
JScrollPane jsp = new JScrollPane(jt);
jf.add(jsp);
jf.setSize(500, 200);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new JTableExample();
}
}
JInternalFrame is a part of Java Swing . JInternalFrame is a container that provides many features of a frame which includes displaying title, opening, closing, resizing, support for menu bar, etc.
Constructors for JInternalFrame
JInternalFrame()
: creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with no titleJInternalFrame(String t)
:creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with a title specified
Example:
import javax.swing.*;
public class JInternalFrameEx {
static JFrame jf;
static JLabel jl;
public static void main(String[] args)
{
jf = new JFrame("frame");
JInternalFrame in = new JInternalFrame();
in.setTitle("InternalFrame");
JButton jb = new JButton("Button");
jl = new JLabel("This is a JInternal Frame.");
JPanel p = new JPanel();
p.add(jl);
p.add(jb);
in.setVisible(true);
in.add(p);
jf.add(in);
jf.setVisible(true);
jf.setSize(300, 300);
}
}
The JDesktopPane class, can be used to create multi-document
applications. A multi-document application can have many windows included in it. We do it by making the contentPane in the main window as an instance of the JDesktopPane class or a subclass. Internal windows add instances of JInternalFrame to the JdesktopPane instance. The internal windows are the instances of JInternalFrame or its subclasses.
Example:
import java.awt.*;
import javax.swing.*;
class CustomDesktopPane extends JDesktopPane {
int numFrames = 3, x = 30, y = 30;
public void display(CustomDesktopPane dp) {
for (int i = 0; i < numFrames; ++i) {
JInternalFrame jframe = new JInternalFrame("Internal Frame " + i, true, true, true, true);
jframe.setBounds(x, y, 250, 85);
Container c1 = jframe.getContentPane();
c1.add(new JLabel("I love my country"));
dp.add(jframe);
jframe.setVisible(true);
y += 85;
}
}
}
public class JDeskPaneEx extends JFrame {
public JDeskPaneEx() {
CustomDesktopPane desktopPane = new CustomDesktopPane();
Container contentPane = getContentPane();
contentPane.add(desktopPane, BorderLayout.CENTER);
desktopPane.display(desktopPane);
setTitle("JDesktopPane Example");
setSize(300, 350);
setVisible(true);
}
public static void main(String args[]) {
new JDeskPaneEx();
}
}
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class SwingCRUD {
private JFrame frame;
private JTextField nameTextField, addressTextField;
private JButton addButton, updateButton, deleteButton;
private JTable table;
private DefaultTableModel tableModel;
private Connection connection;
private Statement statement;
private final String URL = "jdbc:mysql://localhost:3306/school";
private final String USER = "root";
private final String PASSWORD = "";
private void setupUI() {
frame = new JFrame("Student CRUD App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel inputPanel = new JPanel(new GridLayout(10, 2, 10, 10));
inputPanel.setBorder(BorderFactory.createTitledBorder("Student Information"));
nameTextField = new JTextField(10);
addressTextField = new JTextField(10);
inputPanel.add(new JLabel("Name:"));
inputPanel.add(nameTextField);
inputPanel.add(new JLabel("Address:"));
inputPanel.add(addressTextField);
JPanel buttonPanel = new JPanel();
addButton = new JButton("Add");
updateButton = new JButton("Update");
deleteButton = new JButton("Delete");
buttonPanel.add(addButton);
buttonPanel.add(updateButton);
buttonPanel.add(deleteButton);
tableModel = new DefaultTableModel(new Object[]{"ID", "Name", "Address"}, 0);
table = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(inputPanel, BorderLayout.WEST);
frame.add(scrollPane, BorderLayout.EAST);
frame.add(buttonPanel, BorderLayout.SOUTH);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, inputPanel, new JScrollPane(table));
splitPane.setResizeWeight(0.5); // Equal split between the components
frame.add(splitPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addRecord();
}
});
updateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateRecord();
}
});
deleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteRecord();
}
});
}
private void connectToDatabase() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(URL, USER,PASSWORD);
statement = connection.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadTableData() {
try {
ResultSet resultSet = statement.executeQuery("SELECT * FROM student");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String address = resultSet.getString("address");
tableModel.addRow(new Object[]{id, name, address});
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void addRecord() {
String name = nameTextField.getText();
String address = addressTextField.getText();
try {
String query = "INSERT INTO student (name, address) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, name);
preparedStatement.setString(2, address);
preparedStatement.executeUpdate();
tableModel.addRow(new Object[]{getLastInsertedId(), name, address});
} catch (SQLException e) {
e.printStackTrace();
}
}
private int getLastInsertedId() {
try {
ResultSet resultSet = statement.executeQuery("SELECT LAST_INSERT_ID()");
if (resultSet.next()) {
return resultSet.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
private void updateRecord() {
int selectedRowIndex = table.getSelectedRow();
if (selectedRowIndex == -1) {
JOptionPane.showMessageDialog(frame, "Select a row to update.");
return;
}
int id = (int) tableModel.getValueAt(selectedRowIndex, 0);
String name = nameTextField.getText();
String address = addressTextField.getText();
try {
String query = "UPDATE student SET name = ?, address = ? WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, name);
preparedStatement.setString(2, address);
preparedStatement.setInt(3, id);
preparedStatement.executeUpdate();
tableModel.setValueAt(name, selectedRowIndex, 1);
tableModel.setValueAt(address, selectedRowIndex, 2);
} catch (SQLException e) {
e.printStackTrace();
}
}
private void deleteRecord() {
int selectedRowIndex = table.getSelectedRow();
if (selectedRowIndex == -1) {
JOptionPane.showMessageDialog(frame, "Select a row to delete.");
return;
}
int id = (int) tableModel.getValueAt(selectedRowIndex, 0);
try {
String query = "DELETE FROM student WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
tableModel.removeRow(selectedRowIndex);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void run() {
setupUI();
connectToDatabase();
loadTableData();
}
public static void main(String[] args) {
SwingCRUD app = new SwingCRUD();
app.run();
}
}