0% found this document useful (0 votes)
18 views

Java Program

Ajp

Uploaded by

Adarsh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Java Program

Ajp

Uploaded by

Adarsh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

1) Design an applet/application to demonstrate the use of Radio

Button and Checkbox


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class RadioCheckboxDemo extends JFrame {
// Components for radio buttons and checkboxes
private JRadioButton option1, option2, option3;
private JCheckBox checkBox1, checkBox2, checkBox3;
private JButton submitButton;
private JTextArea resultArea;
private ButtonGroup group; // To group radio buttons
public RadioCheckboxDemo() {
// Set up the JFrame
setTitle("Radio Button and Checkbox Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Initialize the components
option1 = new JRadioButton("Option 1");
option2 = new JRadioButton("Option 2");
option3 = new JRadioButton("Option 3");
checkBox1 = new JCheckBox("Checkbox 1");
checkBox2 = new JCheckBox("Checkbox 2");
checkBox3 = new JCheckBox("Checkbox 3");
submitButton = new JButton("Submit");
resultArea = new JTextArea(5, 30);
resultArea.setEditable(false);
// Group radio buttons to allow only one selection at a time
group = new ButtonGroup();
group.add(option1);
group.add(option2);
group.add(option3);
// Add components to the frame
add(option1);
add(option2);
add(option3);
add(checkBox1);
add(checkBox2);
add(checkBox3);
add(submitButton);
add(new JScrollPane(resultArea));
// ActionListener for the submit button
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedOptions = "Selected Option: ";
// Check which radio button is selected
if (option1.isSelected()) {
selectedOptions += "Option 1 ";
} else if (option2.isSelected()) {
selectedOptions += "Option 2 ";
} else if (option3.isSelected()) {
selectedOptions += "Option 3 ";
} else {
selectedOptions += "None ";
}
// Check which checkboxes are selected
String checkBoxes = "Selected Checkboxes: ";
if (checkBox1.isSelected()) {
checkBoxes += "Checkbox 1 ";
}
if (checkBox2.isSelected()) {
checkBoxes += "Checkbox 2 ";
}
if (checkBox3.isSelected()) {
checkBoxes += "Checkbox 3 ";
}
if (!checkBox1.isSelected() && !checkBox2.isSelected() && !checkBox3.isSelected()) {
checkBoxes += "None";
}
// Display the result in the text area
resultArea.setText(selectedOptions + "\n" + checkBoxes);
}
});
}
public static void main(String[] args) {
// Create and display the app
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new RadioCheckboxDemo().setVisible(true);
}
});
}
}
2) 2)Design an applet/application to create form using Text Field,
Text Area, Button and Label.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FormExample extends JFrame {
// Components of the form
private JLabel nameLabel, emailLabel, messageLabel;
private JTextField nameField, emailField;
private JTextArea messageArea;
private JButton submitButton;
private JTextArea resultArea;
public FormExample() {
// Set up the JFrame
setTitle("Form Application");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Initialize form components
nameLabel = new JLabel("Name:");
emailLabel = new JLabel("Email:");
messageLabel = new JLabel("Message:");
nameField = new JTextField(25);
emailField = new JTextField(25);
messageArea = new JTextArea(5, 20);
messageArea.setLineWrap(true); // Allow text wrapping
submitButton = new JButton("Submit");
resultArea = new JTextArea(5, 30);
resultArea.setEditable(false); // Display area is non-editable
// Add components to the frame
add(nameLabel);
add(nameField);
add(emailLabel);
add(emailField);
add(messageLabel);
add(new JScrollPane(messageArea)); // Wrap TextArea in JScrollPane for scrolling
add(submitButton);
add(new JScrollPane(resultArea)); // Wrap result area in JScrollPane
// ActionListener for the submit button
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Get the input from the text fields and text area
String name = nameField.getText();
String email = emailField.getText();
String message = messageArea.getText();
// Display the form data in the result area
resultArea.setText("Form Submitted!\n\n" +
"Name: " + name + "\n" +
"Email: " + email + "\n" +
"Message: " + message);
}
});
}
public static void main(String[] args) {
// Create and display the application window
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FormExample().setVisible(true);
}
});
}
}
3) Develop a program to select multiple languages known to user.
(e. g Marathi, Hindi, English, Sanskrit).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LanguageSelectionApp extends JFrame {
// Components
private JCheckBox marathiCheckBox, hindiCheckBox, englishCheckBox, sanskritCheckBox;
private JButton submitButton;
private JTextArea resultArea;
public LanguageSelectionApp() {
// Set up the JFrame
setTitle("Language Selection");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Initialize checkboxes
marathiCheckBox = new JCheckBox("Marathi");
hindiCheckBox = new JCheckBox("Hindi");
englishCheckBox = new JCheckBox("English");
sanskritCheckBox = new JCheckBox("Sanskrit");
// Initialize submit button
submitButton = new JButton("Submit");
// Initialize result area (non-editable text area to display results)
resultArea = new JTextArea(5, 30);
resultArea.setEditable(false); // Result area should not be editable
// Add components to the frame
add(marathiCheckBox);
add(hindiCheckBox);
add(englishCheckBox);
add(sanskritCheckBox);
add(submitButton);
add(new JScrollPane(resultArea)); // JScrollPane to make the result area scrollable
// ActionListener for the submit button
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// String to store the selected languages
StringBuilder selectedLanguages = new StringBuilder("Languages known to you:\n");
// Check which checkboxes are selected
if (marathiCheckBox.isSelected()) {
selectedLanguages.append("Marathi\n");
}
if (hindiCheckBox.isSelected()) {
selectedLanguages.append("Hindi\n");
}
if (englishCheckBox.isSelected()) {
selectedLanguages.append("English\n");
}
if (sanskritCheckBox.isSelected()) {
selectedLanguages.append("Sanskrit\n");
}
// Display the result
if (selectedLanguages.toString().equals("Languages known to you:\n")) {
resultArea.setText("No languages selected.");
} else {
resultArea.setText(selectedLanguages.toString());
}
}
});
}
public static void main(String[] args) {
// Create and display the application window
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new LanguageSelectionApp().setVisible(true);
}
});
}
}
4) Develop an applet/ application using List components to add
names of 10 different cities
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CityListApp extends JFrame {
// Components
private JList<String> cityList; // JList to display cities
private JScrollPane listScrollPane; // Scroll pane for the list
private JTextArea resultArea; // Text area to show selected city
private JButton submitButton; // Button to submit and display the selected city
// List of 10 cities
private String[] cities = {
"New York", "Los Angeles", "Chicago", "Houston", "Phoenix",
"Philadelphia", "San Antonio", "San Diego", "Dallas", "San Jose"
};
public CityListApp() {
// Set up the JFrame
setTitle("City List Application");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Initialize components
cityList = new JList<>(cities); // Create a list of cities
listScrollPane = new JScrollPane(cityList); // Scroll pane for the list
resultArea = new JTextArea(5, 30); // Text area to show the result
resultArea.setEditable(false); // Make the result area non-editable
submitButton = new JButton("Submit");
// Add components to the frame
add(new JLabel("Select a city:"));
add(listScrollPane); // Add list with scroll pane
add(submitButton); // Add the submit button
add(new JScrollPane(resultArea)); // Add the result area with scroll
// ActionListener for the submit button
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Get the selected city from the list
String selectedCity = cityList.getSelectedValue();
// Check if a city is selected
if (selectedCity != null) {
resultArea.setText("You selected: " + selectedCity);
} else {
resultArea.setText("No city selected.");
}
}
});
}
public static void main(String[] args) {
// Create and display the application window
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CityListApp().setVisible(true);
}
});
}
}
5) Develop applet / application to select multiple names of news
papers

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 class ClickCounter extends JFrame {

private int clickCount = 0;


private JLabel countLabel;

public ClickCounter() {
setTitle("Click Counter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);

countLabel = new JLabel("Click Count: 0");


add(countLabel);

// Add mouse listener to the frame


addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
clickCount++;
countLabel.setText("Click Count: " + clickCount);
}
});

setVisible(true);
}

public static void main(String[] args) {


new ClickCounter();
}
}
20) 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 {
public void init() {
// Set the initial background color of the applet
setBackground(Color.WHITE);
// Add mouse listener to the applet to listen for mouse events
addMouseListener(this);
}
// Override mousePressed method to change the background color
public void mousePressed(MouseEvent e) {
// Generate a random color
Color randomColor = new Color((int) (Math.random() * 0x1000000));
// Set the background color to the random color
setBackground(randomColor);
// Refresh the applet to show the new background color
repaint();
}
// These methods are part of the MouseListener interface but aren't used in this example
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 display a message in the applet
public void paint(Graphics g) {
g.drawString("Click anywhere to change background color", 50, 50);
}
}

OR
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ClickCounter extends JFrame {

private int clickCount = 0;


private JLabel countLabel;

public ClickCounter() {
setTitle("Click Counter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);

countLabel = new JLabel("Click Count: 0");


add(countLabel);

// Add mouse listener to the frame


addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
clickCount++;
countLabel.setText("Click Count: " + clickCount);
}
});

setVisible(true);
}

public static void main(String[] args) {


new ClickCounter();
}
}
21) Write a program using JPasswordField and JTextField to
demonstrate the use of user authentication
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UserAuthenticationDemo extends JFrame {
// Declare UI components
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton;
private JLabel statusLabel;
// Predefined valid username and password for authentication
private static final String VALID_USERNAME = "user";
private static final String VALID_PASSWORD = "password123";
public UserAuthenticationDemo() {
// Set up the frame
setTitle("User Authentication Demo");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center the window on the screen
// Initialize components
usernameField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton("Login");
statusLabel = new JLabel("Please enter your username and password.");
// Create a panel for the form layout
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
// Add components to the panel
panel.add(new JLabel("Username:"));
panel.add(usernameField);
panel.add(new JLabel("Password:"));
panel.add(passwordField);
panel.add(new JLabel()); // Empty label for spacing
panel.add(loginButton);
// Add the panel and status label to the frame
add(panel, BorderLayout.CENTER);
add(statusLabel, BorderLayout.SOUTH);
// Action listener for login button
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
authenticateUser();
}
});
}
// Method to authenticate the user
private void authenticateUser() {
// Get the entered username and password
String username = usernameField.getText();
char[] password = passwordField.getPassword();
// Convert the char[] password to a String for comparison
String passwordString = new String(password);
// Check if the entered credentials match the predefined ones
if (username.equals(VALID_USERNAME) && passwordString.equals(VALID_PASSWORD)) {
statusLabel.setText("Login successful!");
} else {
statusLabel.setText("Invalid username or password.");
}
}
// Main method to launch the program
public static void main(String[] args) {
// Create an instance of UserAuthenticationDemo and make it visible
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new UserAuthenticationDemo().setVisible(true);
}
});
}
}
22) Write a program using JPasswordField to accept password
from user and if the length is less than 6 characters then
error message should be displayed “Password length must be
>6 characters”.
OR
Write a program using JTextField to perform the addition
of two numbers.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy