Java Program
Java Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NewspaperSelectionApp extends JFrame {
// Components
private JCheckBox newspaper1, newspaper2, newspaper3, newspaper4, newspaper5;
private JButton submitButton;
private JTextArea resultArea;
public NewspaperSelectionApp() {
// Set up the JFrame
setTitle("Select Newspapers");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Initialize checkboxes for newspapers
newspaper1 = new JCheckBox("The Times of India");
newspaper2 = new JCheckBox("The Hindu");
newspaper3 = new JCheckBox("The Economic Times");
newspaper4 = new JCheckBox("Hindustan Times");
newspaper5 = new JCheckBox("Deccan Chronicle");
// Initialize the submit button
submitButton = new JButton("Submit");
// Initialize the result area (non-editable text area to display the result)
resultArea = new JTextArea(5, 30);
resultArea.setEditable(false); // Result area should be non-editable
// Add components to the frame
add(new JLabel("Select the newspapers you read:"));
add(newspaper1);
add(newspaper2);
add(newspaper3);
add(newspaper4);
add(newspaper5);
add(submitButton);
add(new JScrollPane(resultArea)); // JScrollPane for result area to enable scrolling
// ActionListener for the submit button
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// String to store selected newspapers
StringBuilder selectedNewspapers = new StringBuilder("Selected Newspapers:\n");
// Check which checkboxes are selected
if (newspaper1.isSelected()) {
selectedNewspapers.append("The Times of India\n");
}
if (newspaper2.isSelected()) {
selectedNewspapers.append("The Hindu\n");
}
if (newspaper3.isSelected()) {
selectedNewspapers.append("The Economic Times\n");
}
if (newspaper4.isSelected()) {
selectedNewspapers.append("Hindustan Times\n");
}
if (newspaper5.isSelected()) {
selectedNewspapers.append("Deccan Chronicle\n");
}
// Display the selected newspapers
if (selectedNewspapers.toString().equals("Selected Newspapers:\n")) {
resultArea.setText("No newspapers selected.");
} else {
resultArea.setText(selectedNewspapers.toString());
}
}
});
}
public static void main(String[] args) {
// Create and display the application window
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new NewspaperSelectionApp().setVisible(true);
}
});
}
}
6)Write java Program to Demonstrate Grid of 5* 5
import javax.swing.*;
import java.awt.*;
public class GridDemo extends JFrame {
public GridDemo() {
// Set up the JFrame
setTitle("5x5 Grid Demo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 5)); // Setting grid layout with 5 rows and 5 columns
// Add 25 buttons to the grid (5x5 grid, total 25 cells)
for (int i = 1; i <= 25; i++) {
JButton button = new JButton("Button " + i); // Create a button with text "Button i"
add(button); // Add the button to the grid
}
// Make the JFrame visible
setVisible(true);
}
public static void main(String[] args) {
// Run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GridDemo(); // Create and display the grid
}
});
}
}
7) Write a program to display The Number on Button from 0 to 9
import javax.swing.*;
import java.awt.*;
public class NumberButtonDemo extends JFrame {
public NumberButtonDemo() {
// Set up the JFrame
setTitle("Number Button Demo");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set the layout for the panel (GridLayout with 2 rows and 5 columns)
setLayout(new GridLayout(2, 5)); // 2 rows and 5 columns, total 10 buttons
// Create buttons with numbers from 0 to 9 and add them to the frame
for (int i = 0; i < 10; i++) {
JButton button = new JButton(String.valueOf(i)); // Create button with number i
add(button); // Add the button to the frame
}
// Make the JFrame visible
setVisible(true);
}
public static void main(String[] args) {
// Run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new NumberButtonDemo(); // Create and display the frame
}
});
}
}
8) Write a program to generate following output using Border
Layout
import javax.swing.*;
import java.awt.*;
public class BorderLayoutDemo extends JFrame {
public BorderLayoutDemo() {
// Set up the JFrame
setTitle("BorderLayout Example");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout()); // Set the layout manager to BorderLayout
// Create buttons or components for each region
JButton northButton = new JButton("North");
JButton southButton = new JButton("South");
JButton eastButton = new JButton("East");
JButton westButton = new JButton("West");
JButton centerButton = new JButton("Center");
// Add the components to the frame with specific positions
add(northButton, BorderLayout.NORTH); // Add button to the North region
add(southButton, BorderLayout.SOUTH); // Add button to the South region
add(eastButton, BorderLayout.EAST); // Add button to the East region
add(westButton, BorderLayout.WEST); // Add button to the West region
add(centerButton, BorderLayout.CENTER); // Add button to the Center region
// Make the JFrame visible
setVisible(true);
}
public static void main(String[] args) {
// Run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new BorderLayoutDemo(); // Create and display the frame
}
});
}
}
9)Write Java program to display following output.
import javax.swing.*;
import java.awt.*;
public class GridBagLayoutDemo extends JFrame {
public GridBagLayoutDemo() {
// Set the title of the frame
setTitle("GridBagLayout Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a GridBagLayout manager
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
// Button 1 - Placing it in the top-left corner
JButton button1 = new JButton("Button 1");
gbc.gridx = 0; // Column 0
gbc.gridy = 0; // Row 0
gbc.gridwidth = 1; // Single cell width
gbc.gridheight = 1; // Single cell height
add(button1, gbc);
// Button 2 - Placing it in the top-right corner
JButton button2 = new JButton("Button 2");
gbc.gridx = 1; // Column 1
gbc.gridy = 0; // Row 0
add(button2, gbc);
// Button 3 - Placing it in the middle center
JButton button3 = new JButton("Button 3");
gbc.gridx = 0; // Column 0
gbc.gridy = 1; // Row 1
gbc.gridwidth = 2; // Spanning across two columns
add(button3, gbc);
// Button 4 - Placing it in the bottom-left corner
JButton button4 = new JButton("Button 4");
gbc.gridx = 0; // Column 0
gbc.gridy = 2; // Row 2
gbc.gridwidth = 1; // Single cell width
gbc.gridheight = 1; // Single cell height
add(button4, gbc);
// Button 5 - Placing it in the bottom-right corner
JButton button5 = new JButton("Button 5");
gbc.gridx = 1; // Column 1
gbc.gridy = 2; // Row 2
add(button5, gbc);
// Make the window visible
setVisible(true);
}
public static void main(String[] args) {
// Create and show the frame
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GridBagLayoutDemo(); // Create and display the GridBagLayout frame
}
});
}
}
10)Write a program which creates Menu of different colors and
disable menu item for Black color.
import javax.swing.*;
import java.awt.event.*;
public class ColorMenuExample extends JFrame {
public ColorMenuExample() {
// Set the title and size of the frame
setTitle("Color Menu Example");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a menu bar
JMenuBar menuBar = new JMenuBar();
// Create a menu for colors
JMenu colorMenu = new JMenu("Colors");
// Create menu items for different colors
JMenuItem redItem = new JMenuItem("Red");
JMenuItem greenItem = new JMenuItem("Green");
JMenuItem blueItem = new JMenuItem("Blue");
JMenuItem blackItem = new JMenuItem("Black"); // This menu item will be disabled
// Add action listeners to handle menu item selection
redItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getContentPane().setBackground(java.awt.Color.RED);
}
});
greenItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getContentPane().setBackground(java.awt.Color.GREEN);
}
});
blueItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getContentPane().setBackground(java.awt.Color.BLUE);
}
});
// The action listener for black is not added, but the item will still exist, but disabled.
blackItem.setEnabled(false); // Disable the Black color menu item
// Add menu items to the color menu
colorMenu.add(redItem);
colorMenu.add(greenItem);
colorMenu.add(blueItem);
colorMenu.add(blackItem); // Black item is added, but it will be disabled
// Add the color menu to the menu bar
menuBar.add(colorMenu);
// Set the menu bar for the frame
setJMenuBar(menuBar);
// Make the frame visible
setVisible(true);
}
public static void main(String[] args) {
// Run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ColorMenuExample(); // Create and display the frame
}
});
}
}
11) Write a program to develop a frame to select the different
states of India using JComboBox .
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StateSelectionFrame extends JFrame {
public StateSelectionFrame() {
// Set the title of the frame
setTitle("Select State of India");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a JComboBox with a list of Indian states
String[] states = {
"Andhra Pradesh", "Arunachal Pradesh", "Assam"};
JComboBox<String> stateComboBox = new JComboBox<>(states);
// Create a label to display the selected state
JLabel selectedStateLabel = new JLabel("Selected State: None");
// Add ActionListener to JComboBox to handle state selection
stateComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedState = (String) stateComboBox.getSelectedItem();
selectedStateLabel.setText("Selected State: " + selectedState);
}
});
// Set the layout manager for the frame
setLayout(new FlowLayout());
// Add the JComboBox and the JLabel to the frame
add(stateComboBox);
add(selectedStateLabel);
// Make the frame visible
setVisible(true);
}
public static void main(String[] args) {
// Run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new StateSelectionFrame(); // Create and display the frame
}
});
}
}
12) Develop a program to demonstrate the use of ScrollPane in
Swings
import javax.swing.*;
import java.awt.*;
public class ScrollPaneExample extends JFrame {
public ScrollPaneExample() {
// Set the title of the frame
setTitle("JScrollPane Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a JTextArea
JTextArea textArea = new JTextArea(15, 30); // 15 rows, 30 columns
textArea.setText("this is athrava gujar in diploma TYIF and here to represent a my pratical exam that
will allow");
// Set the text area to be non-editable (optional)
textArea.setEditable(false); // This makes the text area read-only
// Create a JScrollPane to make the JTextArea scrollable
JScrollPane scrollPane = new JScrollPane(textArea);
// Add the JScrollPane to the frame
add(scrollPane);
// Make the frame visible
setVisible(true);
}
public static void main(String[] args) {
// Create the frame and run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ScrollPaneExample(); // Create and display the frame
}
});
}
}
13)Develop a program to demonstrate the use of tree component
in
swing.
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class TreeExample extends JFrame {
public TreeExample() {
// Set the title of the frame
setTitle("JTree Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create the root node
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Categories");
// Create the child nodes under the root
DefaultMutableTreeNode electronics = new DefaultMutableTreeNode("Electronics");
DefaultMutableTreeNode books = new DefaultMutableTreeNode("Books");
DefaultMutableTreeNode clothes = new DefaultMutableTreeNode("Clothes");
// Create further child nodes for the "Electronics" node
DefaultMutableTreeNode laptops = new DefaultMutableTreeNode("Laptops");
DefaultMutableTreeNode mobiles = new DefaultMutableTreeNode("Mobiles");
electronics.add(laptops);
electronics.add(mobiles);
// Create further child nodes for the "Books" node
DefaultMutableTreeNode fiction = new DefaultMutableTreeNode("Fiction");
DefaultMutableTreeNode nonFiction = new DefaultMutableTreeNode("Non-Fiction");
books.add(fiction);
books.add(nonFiction);
// Create further child nodes for the "Clothes" node
DefaultMutableTreeNode men = new DefaultMutableTreeNode("Men");
DefaultMutableTreeNode women = new DefaultMutableTreeNode("Women");
clothes.add(men);
clothes.add(women);
// Add the child nodes to the root
root.add(electronics);
root.add(books);
root.add(clothes);
// Create a JTree with the root node
JTree tree = new JTree(root);
// Add the JTree to a JScrollPane to make it scrollable
JScrollPane treeScrollPane = new JScrollPane(tree);
// Add the JScrollPane to the frame
add(treeScrollPane);
// Set the frame visible
setVisible(true);
}
public static void main(String[] args) {
// Run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TreeExample(); // Create and display the frame
}
});
}
}
14) Develop a program to demonstrate the use of JTable.
import javax.swing.*;
import java.awt.*;
public class JTableExample extends JFrame {
public JTableExample() {
// Set the title of the frame
setTitle("JTable Example");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Define the column names
String[] columnNames = {"Name", "Age", "City"};
// Define some data for the table
Object[][] data = {
{"Alice", 25, "New York"},
{"Bob", 30, "Los Angeles"},
{"Charlie", 35, "Chicago"},
{"David", 40, "Miami"},
{"Eve", 22, "San Francisco"}
};
// Create a JTable with the data and column names
JTable table = new JTable(data, columnNames);
// Set the table in a JScrollPane to allow scrolling
JScrollPane scrollPane = new JScrollPane(table);
// Add the JScrollPane to the frame
add(scrollPane, BorderLayout.CENTER);
// Make the frame visible
setVisible(true);
}
public static void main(String[] args) {
// Run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JTableExample(); // Create and display the frame
}
});
}
}
15) Write a program code to generate the following output
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
public class StudentTableExample extends JFrame {
public StudentTableExample() {
// Set the title of the frame
setTitle("Student Table Example");
setSize(400, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Define the column names
String[] columnNames = {"ID", "Name", "Salary"};
// Define the data for the table
Object[][] data = {
{1, "Alice", "1000"},
{2, "Bob", "2000"},
{3, "Charlie", "3000"}
};
// Create a DefaultTableModel with the data and column names
DefaultTableModel model = new DefaultTableModel(data, columnNames);
// Create a JTable with the DefaultTableModel
JTable table = new JTable(model);
// Set the table in a JScrollPane to allow scrolling
JScrollPane scrollPane = new JScrollPane(table);
// Add the JScrollPane to the frame
add(scrollPane, BorderLayout.CENTER);
// Make the frame visible
setVisible(true);
}
public static void main(String[] args) {
// Run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new StudentTableExample(); // Create and display the frame
}
});
}
}
16)Write a Java program to create a table of Name of Student,
Percentage and Grade of 5 students using JTable.
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
public class StudentGradeTable extends JFrame {
public StudentGradeTable() {
// Set the title of the frame
setTitle("Student Grades Table");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Define the column names
String[] columnNames = {"Name", "Percentage", "Grade"};
// Define the data for the table
Object[][] data = {
{"Alice", 85.5, "A"},
{"Bob", 72.3, "B"},
{"Charlie", 90.0, "A"},
{"David", 65.2, "C"},
{"Eve", 78.9, "B"}
};
// Create a DefaultTableModel with the data and column names
DefaultTableModel model = new DefaultTableModel(data, columnNames);
// Create a JTable with the DefaultTableModel
JTable table = new JTable(model);
// Set the table in a JScrollPane to allow scrolling
JScrollPane scrollPane = new JScrollPane(table);
// Add the JScrollPane to the frame
add(scrollPane, BorderLayout.CENTER);
// Make the frame visible
setVisible(true);
}
public static void main(String[] args) {
// Run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new StudentGradeTable(); // Create and display the frame
}
});
}
}
17) Write a program code to generate the following output
import javax.swing.*;
import java.awt.*;
public class ProgressBarExample extends JFrame {
// Constructor for the ProgressBarExample class
public ProgressBarExample() {
// Set the title of the frame
setTitle("Progress Bar Example");
setSize(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a JProgressBar with a range from 0 to 100 (for 100% progress)
JProgressBar progressBar = new JProgressBar(0, 100);
// Set the initial value of the progress bar to 0
progressBar.setValue(0);
// Set the progress bar to be indeterminate initially (if desired)
progressBar.setStringPainted(true); // Display the percentage text on the bar
// Create a button that will simulate the progress (you can use a timer to increment the progress)
JButton startButton = new JButton("Start");
// Add an ActionListener to the button to simulate progress
startButton.addActionListener(e -> {
// Create a worker thread that will update the progress bar
new Thread(() -> {
for (int i = 0; i <= 100; i++) {
try {
// Simulate some work being done by sleeping for 50 milliseconds
Thread.sleep(50);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
// Update the value of the progress bar
progressBar.setValue(i);
}
}).start();
});
// Add the progress bar and button to the frame
setLayout(new BorderLayout());
add(progressBar, BorderLayout.CENTER);
add(startButton, BorderLayout.SOUTH);
// Make the frame visible
setVisible(true);
}
public static void main(String[] args) {
// Run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(() -> new ProgressBarExample());
}
}
18) Write a program to generate KeyEvent when a key is pressed
and display “Key Pressed” message.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class KeyEventExample extends JFrame {
private JLabel messageLabel;
public KeyEventExample() {
// Set up the frame
setTitle("Key Event Example");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a label to display the message
messageLabel = new JLabel("Press any key", JLabel.CENTER);
messageLabel.setFont(new Font("Arial", Font.BOLD, 20));
// Add the label to the frame
add(messageLabel);
// Add a KeyListener to the frame to listen for key events
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// When a key is pressed, display the message
messageLabel.setText("Key Pressed: " + KeyEvent.getKeyText(e.getKeyCode()));
}
});
// Set the frame to be focusable to capture key events
setFocusable(true);
setFocusTraversalKeysEnabled(false);
// Make the frame visible
setVisible(true);
}
public static void main(String[] args) {
// Run the program on the Event Dispatch Thread
SwingUtilities.invokeLater(() -> new KeyEventExample());
}
}
19) Write a program to change the background color of Applet
when user performs events using Mouse
or
Write a program to count the number of clicks performed by the
user in a Frame window
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class MouseEventApplet extends Applet implements MouseListener {
// Constructor for the applet
public void init() {
// Set the background color initially
setBackground(Color.WHITE);
// Add mouse listener to the applet
addMouseListener(this);
}
// Override mousePressed to change the background color when the mouse is pressed
public void mousePressed(MouseEvent e) {
// Change the background color randomly on mouse press
setBackground(new Color((int)(Math.random() * 0x1000000)));
repaint();
}
// These methods are not used, but they need to be implemented because of MouseListener
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
// Override the paint method to refresh the applet
public void paint(Graphics g) {
g.drawString("Click to change background color!", 50, 60);
}
}
Or
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public ClickCounter() {
setTitle("Click Counter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setVisible(true);
}
OR
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public ClickCounter() {
setTitle("Click Counter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setVisible(true);
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PasswordValidationDemo extends JFrame {
// Declare UI components
private JPasswordField passwordField;
private JButton submitButton;
private JLabel messageLabel;
public PasswordValidationDemo() {
// Set up the frame
setTitle("Password Validation Demo");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center the window on the screen
// Initialize components
passwordField = new JPasswordField(20);
submitButton = new JButton("Submit");
messageLabel = new JLabel("Enter your password:", JLabel.CENTER);
// Set up the layout
setLayout(new GridLayout(3, 1));
// Add components to the frame
add(messageLabel);
add(passwordField);
add(submitButton);
// Add action listener to the submit button
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
validatePassword();
}
});
}
// Method to validate password length
private void validatePassword() {
// Get the entered password as a char array
char[] password = passwordField.getPassword();
// Check if the length of the password is less than 6 characters
if (password.length < 6) {
// Display error message
JOptionPane.showMessageDialog(this, "Password length must be > 6 characters", "Error",
JOptionPane.ERROR_MESSAGE);
} else {
// If the password is valid (6 or more characters)
JOptionPane.showMessageDialog(this, "Password is valid!", "Success",
JOptionPane.INFORMATION_MESSAGE);
}
}
// Main method to launch the program
public static void main(String[] args) {
// Create and display the password validation frame
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PasswordValidationDemo().setVisible(true);
}
});
}
}
OR
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AdditionProgram extends JFrame {
// Declare UI components
private JTextField num1Field;
private JTextField num2Field;
private JButton addButton;
private JLabel resultLabel;
public AdditionProgram() {
// Set up the frame
setTitle("Addition Program");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center the window on the screen
// Initialize components
num1Field = new JTextField(15);
num2Field = new JTextField(15);
addButton = new JButton("Add");
resultLabel = new JLabel("Result: ", JLabel.CENTER);
// Set up the layout
setLayout(new GridLayout(4, 2));
// Add components to the frame
add(new JLabel("Enter first number:"));
add(num1Field);
add(new JLabel("Enter second number:"));
add(num2Field);
add(addButton);
add(resultLabel);
// Add action listener to the add button
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performAddition();
}
});
}
// Method to perform addition and display the result
private void performAddition() {
try {
// Get the text from both text fields
String num1Text = num1Field.getText();
String num2Text = num2Field.getText();
// Convert the input text to numbers (double)
double num1 = Double.parseDouble(num1Text);
double num2 = Double.parseDouble(num2Text);
// Perform addition
double sum = num1 + num2;
// Display the result
resultLabel.setText("Result: " + sum);
} catch (NumberFormatException e) {
// If input is not valid (not a number), show an error message
resultLabel.setText("Invalid input. Please enter numbers.");
}
}
// Main method to launch the program
public static void main(String[] args) {
// Create and display the addition frame
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new AdditionProgram().setVisible(true);
}
});
}
}
23) Write a Program to create a Student Table in database and
insert a record in a Student table