Swing Is A Java GUI

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

Practical

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SwingAddition


{
public static void main(String args[])
{
Abc obj=new Abc();
}
}

class Abc extends JFrame implements ActionListener


{
JLabel l1;
JTextField t1;
JLabel l2;
JTextField t2;
JButton b;
JLabel l3;

public Abc()
{
setLayout(new FlowLayout());

l1=new JLabel("First Number:");


t1=new JTextField(20);

l2=new JLabel("Second Number:");


t2=new JTextField(20);

b=new JButton("Add");

l3=new JLabel("Result");

add(l1);
add(t1);
add(l2);
add(t2);
add(b);
add(l3);

b.addActionListener(this);
setVisible(true);
setSize(250,400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent ae)


{
int num1=Integer.parseInt(t1.getText());
int num2=Integer.parseInt(t2.getText());

int value=num1+num2;
l3.setText(""+value);
}

Swing is a Java GUI (Graphical User Interface) framework that allows developers to create
desktop applications with graphical user interfaces. It is a part of the Java Foundation Classes
(JFC) and provides a set of components and libraries for building interactive and visually
appealing desktop applications. Here are some detailed notes on Swing in Java:

1. Swing Components:
 Swing provides a wide range of components like buttons, labels, text fields, check boxes,
radio buttons, sliders, and more for building the user interface of your application.
 These components are lightweight, which means they do not rely on the native
platform's windowing system, making Swing applications highly portable across different
operating systems.
2. MVC Architecture:
 Swing follows the Model-View-Controller (MVC) architectural pattern, which helps in
separating the application's logic from its presentation.
 Models represent the data, Views display the data, and Controllers handle user input and
interact with models.
3. Event Handling:
 Swing components generate various events (e.g., button clicks, mouse movements,
keyboard input).
 Event listeners are used to handle these events, and Swing provides a rich set of listener
interfaces and adapters to simplify event handling.
4. Layout Management:
 Swing offers several layout managers to arrange components within containers.
Common layout managers include BorderLayout, FlowLayout, GridLayout, and
BoxLayout.
 Layout managers help ensure that your GUI components are organized and displayed
correctly.
5. Customization:
 Swing components are highly customizable. You can change their appearance and
behavior by setting properties and using custom rendering.
 You can also create custom Swing components by extending existing ones or creating
entirely new components.
6. Thread Safety:
 Swing is not thread-safe by default. All Swing components should be accessed and
modified from the Event Dispatch Thread (EDT) to prevent synchronization issues.
 The SwingUtilities class provides utility methods for working with the EDT.
7. Internationalization and Localization:
 Swing supports internationalization (i18n) and localization (l10n) through the use of
resource bundles, which allows you to create applications that can be easily translated
into different languages.
8. LookAndFeel:
 Swing applications can have different look and feel (L&F) styles to match the native
appearance of the underlying operating system. Common L&Fs include Metal, Windows,
and Nimbus.
9. Swing vs. AWT:
 Swing is often compared to AWT (Abstract Window Toolkit), another Java GUI
framework.
 Swing is more powerful and flexible than AWT, as it provides lightweight components, a
richer set of widgets, and a consistent look and feel across platforms.
10. Swing in Modern Java:
 Swing is still relevant for developing desktop applications in Java, but it's important to
note that JavaFX and other alternatives have gained popularity in recent years.
 JavaFX, in particular, offers more modern features and better integration with Java,
making it a viable choice for new projects.
11. Development Tools:
 Popular Java IDEs like Eclipse, IntelliJ IDEA, and NetBeans provide extensive support for
Swing development, including visual GUI builders to simplify the design process.
12. Documentation and Resources:
 There are many online tutorials, books, and community forums available to learn and get
help with Swing development.
 The official Oracle documentation and the Java Swing Trail are good starting points for
learning Swing.

In summary, Swing i
working with Swing in Java to create graphical user interfaces (GUIs) for desktop applications:

1. Setting Up Your Development Environment:


 Make sure you have Java Development Kit (JDK) installed on your system.
 Use an Integrated Development Environment (IDE) like Eclipse, IntelliJ IDEA, or NetBeans,
which offer built-in tools for Swing development.
2. Import Swing Packages:
 To use Swing components, import the necessary packages at the beginning of your Java
file:
import javax.swing.*;

import java.awt.*;

2/2
Certainly! Here are some practical notes and tips for working with Swing in Java to create
graphical user interfaces (GUIs) for desktop applications:

1. Setting Up Your Development Environment:


 Make sure you have Java Development Kit (JDK) installed on your system.
 Use an Integrated Development Environment (IDE) like Eclipse, IntelliJ IDEA, or NetBeans,
which offer built-in tools for Swing development.
2. Import Swing Packages:
 To use Swing components, import the necessary packages at the beginning of your Java
file:
javaCopy code
import javax.swing.*; import java.awt.*;
3. Creating a Swing JFrame:
 The JFrame class is the main window of your Swing application.
 Create an instance of JFrame, set its properties, and add components to it.
JFrame frame = new JFrame("My Swing Application");

frame.setSize(400, 300);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

4. Adding Components:
 Use various Swing components like JButton, JLabel, JTextField, etc., to design your
GUI.
 Add components to the JFrame using its add() method:
JButton button = new JButton("Click Me");

frame.add(button);
Layout Managers:
 Choose an appropriate layout manager (e.g., FlowLayout, GridLayout, BorderLayout) to
arrange your components within the JFrame.
button.addActionListener(new ActionListener()

public void actionPerformed(ActionEvent e) {

// Handle button click here

});

Event Handling:
 Implement event listeners to handle user interactions (e.g., button clicks).
 Use addActionListener() to attach an action listener to a button:
button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

// Handle button click here

});

Running the Application:


 After adding components and configuring your JFrame, make it visible and run the
application by calling setVisible(true):
frame.setVisible(true);

Swing Threading:
 Always update Swing components from the Event Dispatch Thread (EDT) to ensure
thread safety:
SwingUtilities.invokeLater(new Runnable() {

public void run() {


// Code to update Swing components

});

Dialogs and Pop-up Windows:


 Use JOptionPane for simple message dialogs and pop-up windows.
JOptionPane.showMessageDialog(frame, "Hello, Swing!");

Internationalization (i18n) and Localization (l10n):


 Externalize strings and labels using resource bundles to make your application easily
translatable.
Look and Feel (L&F):
 Change the look and feel of your application by setting the UIManager's L&F:
Hello, Swing! - A basic Swing application with a button that displays a message when clicked:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class HelloWorldSwing {


public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
public void run()
{
JFrame frame = new JFrame("Hello, Swing!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton button = new JButton("Click Me");


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Hello, Swing!");
}
});

frame.getContentPane().add(button);
frame.setPreferredSize(new Dimension(300, 100));
frame.pack();
frame.setVisible(true);
}
});
}
}

Simple Calculator - A Swing application that implements a basic calculator with buttons for
digits and arithmetic operations:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleCalculator {


public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Simple Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTextField display = new JTextField(10);


display.setEditable(false);
frame.add(display, BorderLayout.NORTH);

JPanel buttonPanel = new JPanel(new GridLayout(4, 4));

String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};

for (String label : buttonLabels)


{
JButton button = new JButton(label);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String text = display.getText();
String command = e.getActionCommand();

if ("C".equals(command)) {
display.setText("");
} else if ("=".equals(command)) {
try {
String result = String.valueOf(evalExpression(text));
display.setText(result);
} catch (Exception ex) {
display.setText("Error");
}
} else {
display.setText(text + command);
}
}
});
buttonPanel.add(button);
}
frame.add(buttonPanel, BorderLayout.CENTER);

frame.setPreferredSize(new Dimension(300, 400));


frame.pack();
frame.setVisible(true);
}
});
}

private static double evalExpression(String expression) {


return new ScriptEngineManager()
.getEngineByName("JavaScript")
.eval(expression);
}
}

You might also like