0% found this document useful (0 votes)
14 views18 pages

Java Exp.8,9,10,11

Java program for content sorting,creating analog clock using applet,create calculator using swings,crateing ms word using swings

Uploaded by

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

Java Exp.8,9,10,11

Java program for content sorting,creating analog clock using applet,create calculator using swings,crateing ms word using swings

Uploaded by

princetaak1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
input.txt: suresh 56 Mahesh 89 Shyam 61 Vikas 92 Shloka 84 Nalini 62 Abhi 71 Bhavani 68 SOURCE CODE: // sorting the content of a given text file import java.io. BufferedReader, import java.io.ButferedWriter; import java.io FileReader, import java.io.FileWriter; import java.io.]OExceptior import java.util ArrayList; import java.util.Collections; import java.util. Comparator, 1 Student Class class Student { String name; int marks; Public Student(String name, int marks) { this.name = name; this. marks = marks; } } 1 nameCompare Class to compare the names class NameCompare implements Comparator { @Override public int compare(Student s1, Student s2) { retum s1.name.compareTo(s2.name); } } 1 marksCompare Class to compare the marks class MarksCompare implements Comparator { @Override public int compare(Student s1, Student s2) { return s2.marks - s1.marks; 7 } public class SortTextFile { public static void main(Stringl] args) { try{ 1! Creating BufferedReader object to read the input text file BufferedReader reader = new BufferedReader(new FileReader("input txt"); 11 Creating ArrayList to hold Student objects ArrayList studentRecords = new ArrayList<>(); // Reading Student records one by one String currentLine = reader.readLine(); while (currentLine != null) { Stringl} studentDetail = currentLine.split(""); String name = studentDetail(0}; int marks = Integer.valueOf(studentDetaill1)); 1/ Creating Student object for every student record and adding it to ArrayList studentRecords.add(new Student(name, marks)); currentLine = reader.readLine(); 2 // Closing the reader reader.close(); // Sorting ArrayList studentRecords based on marks Collections.sort(studentRecords, new MarksCompare()); 11 Creating BufferedWriter object to write into output text file BufferedWriter writer = new ButferedWriter(new FileWriter(“output.txt")); J Mriting every studentRecords into output text file for (Student student : studentRecords) { writer.write(student.name); writer.write(” " + student. marks); writer.newLine(); } 11 Closing the writer writer.close(); } catch (IOException e) { e.printStackTrace(); } } } OUTPUT: output.txt : Vikas 92 Mahesh 89 Shloka 84 Shyam 81 Abhi 71 Bhavani 68 Nalini 62 Suresh 56 SOURCE CODE: // to develop an analog clock using an applet . // Java program to illustrate // analog clock using Applets import java.applet. Applet import java.awt.*; import java.util.*; public class analogClock extends Applet { @override public void init() { // Applet window size & color this.setSize(new Dimension(800, 400)); setBackground(new Color (50, 50, 50); new Taread() { @override public void run() { while (true) { repaint(); delayAnimation() ; } }.start(); } // Animating the applet private void delayAnimation() { try { // Animation delay is 1000 milliseconds Thread. sleep (1000) ; } catch (InterruptedException e) { e.printStackTrace() ; } } // Paint the applet @override public void paint (Graphics g) { // Get the system time Calendar time = Calendar.getInstance() ; int hour = time.get (Calendar .HOUR_OF_DAY) ; int minute = time.get (Calendar .MINUTE) ; int second = time. get (Calendar SECOND) ; // 12 hour format if (hour > 12) { hour -= 12; } // Draw clock body center at (400, 200) g.setColor (Color.white) ; g.£illoval (300, 100, 200, 200); // Labeling g.setColor (Color .black) ; g.drawString("12", 390, 120); g-drawString("9", 310, 200); g.drawString("6", 400, 290); g.drawstring("3", 480, 200); // Declaring variables to be used double angle; int x, yi // Second hand's angle in Radian angle = Math.toRadians((15 - second) * 6); // Position of the second hand // with length 100 unit x = (int) (Math.cos (angle) * 100); y = (int) (Math.sin (angle) * 100); // Red color second hand g.setColor (Color. red) ; gG.drawLine(400, 200, 400 + x, 200 - y); // Minute hand's angle in Radian angle = Math. toRadians((15 - minute) * 6); // Position of the minute hand // with length 80 unit x = (int) (Math.cos (angle) * 80); y = (int) (Math.sin(angle) * 80); // blue color Minute hand g.setColor (Color .blue) ; g.drawLine (400, 200, 400 + x, 200 - y); // Hour hand's angle in Radian angle = Math.toRadians((15 - (hour * 5)) * 6); // Position of the hour hand // with length 50 unit x = (int) (Math.cos (angle) * 50); y = (int) (Math.sin (angle) * 50); // Black color hour hand g.setColor (Color.black) ; g-drawLine (400, 200, 400 + x, 200 - y); Here's the HTML code to embed the applet: OUTPUT: This will display a clock with moving hour, minute, and second hands to represent the current time. Tle SOURCE CODE: // to develop a scientific calculator using swings. import javax.swing.*; import java.awt.*; import java.awt.event."; class Calculator extends JFrame implements ActionListener { private static final long serialVersionUID = 1; // Adding serial version UID 1/ Declare components private JTextField displayField; private String operand1, operand2, operator, /{ Constructor Calculator() { operandi = operand2 = operator = ""; J Set up the frame sefTitle(*Calculator’); setSize(300, 400); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new BorderLayout()); 11 Create and add display field displayField = new JTextField(16); displayField.setEditable(false); add(displayField, BorderLayout. NORTH); // Create and add button panel JPanel buttonPanel = new JPanel(new GridLayout(s, 4)); addButtons(buttonPanel); add(buttonPanel, BorderLayout CENTER); } /{ Method to add buttons to the panel private void addButtons(JPanel panel) { String[] buttonLabels T "9", "4", hk for (String label : buttonLabels) { Button button = new JButton(label); button.addActionListener(this); panel.add(button); } ) 1/ ActionListener implementation Public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); switch (command) { case 'C’ clearDisplay(); break; case" calculateResult(); break; case "+" case" case case": setOperator(command); break; default: appendToDisplay(command); break; } } // Method to append a digit or decimal point to the display private void appendToDisplay(String input) { if (operator.isEmpty()) { operand! += input; displayField.setText(operand1); }else { operand2 += input; displayField.setText(operand2); } } 1 Method to set the operator private void setOperator(String op) { operator = op; displayField.setText(operandt + operator); } // Method to calculate and display the result private void calculateResult() { if (loperand1 .isEmpty() && loperand2.isEmpty() && !operator.isEmpty()) { double result = 0; double num = Double.parseDouble(operand1); double num2 = Double. parseDouble(operand2); switch (operator) { case "+": result = numt + num2; breal case"! result = numt - num2; break; case "*": result = num1 * num2; breal case": if (num2 != 0) ( result = numt /num2; jelse { JOptionPane.showMessageDialog(this, "Error: Division by zero", "Error", JOptionPane.ERROR_MESSAGE); clearDisplay(); retum; } break; } displayField.setText(String.valueOf(result); operand! = String.valueOf(result); operand2 = operatoi } } // Method to clear the display and reset operands and operator private void clearDisplay() { operand! = operand? = operator displayField.setText("); } /{ Main method Public static void main(String[] args) { ‘SwingUtilities.invokeLater(() -> { new Calculator().setVisible(true); ym } } OUTPUT: laa. oO x P+ oe | Ty T-]-]— —) SOURCE CODE: //Create an editor like MS-word using swings import javax.swing.*; import javax.swing.event. DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.undo.UndoableEdit; // Add this import for UndoableEdit import java.awt." import java.awt.event.*; import java.io"; import java.util ArrayList; import java.awt.print.Printerxception; // Add this import for PrinterException class Editor extends JFrame implements ActionListener, DocumentListener { private static final long serialVersionUID = private JTextArea textArea; private File currentFile; private boolean isTextModified; private ArrayList undoBuffer; private ArrayList redoButfer; Editor() ( 11 Create the fram sefTitle("Text Editor setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); setSize(800, 600); setLocationRelativeTo(null); // Create a menu bar JMenuBar menuBar = new JMenuBar(); // Create File menu JMenu fileMenu = new JMenu("File"); JMenultem newMenultem = new JMenultem("New’); JMenultem openMenultem = new JMenultem("Open'); JMenultem saveMenultem = new JMenultem("Save"); JMenultem saveAsMenultem = new JMenultem("Save As"); JMenultem printMenultem = new JMenultem('Print’); JMenultem exitMenultem = new JMenultem("Exit"); /) Add action listeners to File menu items newMenultem.addActionListener (this); ‘openMenultem.addActionListener(thi saveMenultem.addActionListener(this); saveAsMenultem.addActionListener(this); printMenultem.addActionListener (this); exitMenultem.addActionListener(this); 1/ Add File menu items fileMenu.add(newMenultem); fileMenu.add(openMenultem); fileMenu.add(saveMenultem); fileMenu.add(saveAsMenultem); fileMenu.addSeparator(); fileMenu.add(printMenultem); fileMenu.addSeparator(); ileMMenu.add(exitMenultem); Create Edit menu JMenu editMenu = new JMenu("Edit"); JMenultem undoMenultem = new JMenultem("Undo’); JMenultem redoMenultem = new JMenultem("Redo") JMenultem cutMenultem = new JMenultem("Cut"); JMenultem copyMenultem = new JMenultem("Copy"); JMenultem pasteMenultem = new JMenultem("Paste"); 1] Add action listeners to Edit menu items undoMenultem.addActionListener(this); redoMenultem.addActionListener(this); cutMenultem.addActionListener(this); copyMenultem.addActionListener(this); pasteMenultem.addAction Listener(this); 11 Add Edit menu items editMenu.add(undoMenultem); editMenu.add(redoMenultem); editMenu.addSeparator(); editMenu.add(cutMenultem); editMenu.add(copyMenultem); editMenu.add(pasteMenultem); 1] Add menus to menu bar menuBar.add{ileMenu); menuBar.add(editMenu); 11 Set menu bar to frame setJMenuBar(menuBar); 1 Create text area textArea = new JTextArea(): textArea.getDocument().addDocumentListener (this); JSorollPane scrollPane = new JScrollPane(textArea); 1/ Add text area to frame add(scroliPane, BorderLayout. CENTER); currentFile = null; isTextModified = false; undoButfer = new ArrayList<>(); redoBuffer = new ArrayList<>(); 1] Add window listener for closing the application addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { closeEditor(); } ys 1/ Set frame visible setVisible(true); } Public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); switch (command) { case "New: newFile(); break; case "Open openFile(); break; case "Save": saveFile(); break; case "Save As": saveFileAs(); break; case "Print printFile(); break; case "Undo": undoEdit(); break; case "Redo’ redoEdit(); break; case "Cut": textArea.cut(); break; case "Copy": textArea.copy(): break; case "Paste" textArea paste); break; case "Exit': closeEditor(); break; default: break; } } private void newFile() { if (isTextModified) { int choice = JOptionPane.showConfirmDialog(this, "Do you want to save changes to the current file?", "Save changes", JOptionPane.YES_NO_CANCEL_OPTION); if (choice == JOptionPane.YES_OPTION) { saveFile(); } else if (choice == JOptionPane.CANCEL_OPTION) { retum; } } textArea.setText("); currentFile = null; isTextModified = false; setTitle("Text Editor"); } private void openFile() { JFileChooser fileChooser = new JFileChooser(); int response = fileChooser.showOpenDialogi(this); if (response == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try (ButferedReader reader = new ButferedReader(new FileReader(file))) StringBuilder text = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { text.appendi(ine).append("\n"); } textArea.setText(text.toString()); currentFile = file; TextModified = false; setTitle("Text Editor - " + file.getName()); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "Error opening file: "+ ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } private void saveFile() { if (currentFile == null) { saveFileAs(); }else { try (BufferedWriter writer = new BufferedWriter(new FileWriter(currentFile))) { writer.write(textArea.getText()); isTextModified = false; }eatch (IOException ex) { JOptionPane.showMessageDialog(this, "Error saving file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } private void saveFileAs() { JFileChooser fileChooser = new JFileChooser(); int response = fileChooser.showSaveDialog(this); if (response == JFileChooser. APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { writer.write(textArea.getText()); currentFile = file; ‘extModified = false; setTitle("Text Editor - " + file.getName()); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "Error saving file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } private void printFile() { try{ textArea print(); } catch (PrinterException ex) { JOptionPane.showMessageDialog(this, "Error printing file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } private void undoEdit() { if (undoButfer.isEmpty()) { UndoableEdit edit = undoButfer.remove(undoButfer.size() - 1); redoButfer.add\edit); edit.undo(); } } private void redoEdit() { if (redoButfer.isEmpty()) { UndoableEdit edit = redoButfer.remove(redoButfer.size() - 1); undoButfer.add(edit); edit redo); } } private void closeEditor() { if (isTextModified) { int choice = JOptionPane.showConfirmDialog(this, "Do you want to save changes to the current file?", "Save changes", JOptionPane.YES_NO_CANCEL_OPTION); if (choice == JOptionPane. YES_OPTION) { saveFile(); } else if (choice == JOptionPane.CANCEL_OPTION) { return; } } dispose(); } i DocumentListener methods @Override public void insertUpdate(DocumentEvent e) { isTextModified = true; 2 @Override public void removeUpdate(DocumentEvent e) { isTextModified = true; Z @Override public void changedUpdate(DocumentEvent e) { isTextModified = true; } public static void main(String[] args) { new Editor() } } —_ x] at ce |

You might also like