Bitcoin

Bitcoin
Bitcoin

Text Editor using java programming language

 Here’s a simple Java text editor program using Swing. It provides a window with basic functionality to create, open, edit, and save text files.


Code:


import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.io.*;


public class SimpleTextEditor extends JFrame implements ActionListener {

    JTextArea textArea;

    JScrollPane scrollPane;

    JMenuBar menuBar;

    JMenu fileMenu;

    JMenuItem newFile, openFile, saveFile, exitApp;


    public SimpleTextEditor() {

        // Window Title

        setTitle("Simple Text Editor");

        setSize(600, 400);

        setDefaultCloseOperation(EXIT_ON_CLOSE);


        // Text Area

        textArea = new JTextArea();

        scrollPane = new JScrollPane(textArea);

        add(scrollPane);


        // Menu Bar

        menuBar = new JMenuBar();

        fileMenu = new JMenu("File");


        newFile = new JMenuItem("New");

        openFile = new JMenuItem("Open");

        saveFile = new JMenuItem("Save");

        exitApp = new JMenuItem("Exit");


        newFile.addActionListener(this);

        openFile.addActionListener(this);

        saveFile.addActionListener(this);

        exitApp.addActionListener(this);


        fileMenu.add(newFile);

        fileMenu.add(openFile);

        fileMenu.add(saveFile);

        fileMenu.add(exitApp);

        menuBar.add(fileMenu);


        setJMenuBar(menuBar);

        setVisible(true);

    }


    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == newFile) {

            textArea.setText("");

        } else if (e.getSource() == openFile) {

            JFileChooser fileChooser = new JFileChooser();

            int option = fileChooser.showOpenDialog(this);

            if (option == JFileChooser.APPROVE_OPTION) {

                try (BufferedReader br = new BufferedReader(new FileReader(fileChooser.getSelectedFile()))) {

                    textArea.read(br, null);

                } catch (IOException ex) {

                    ex.printStackTrace();

                }

            }

        } else if (e.getSource() == saveFile) {

            JFileChooser fileChooser = new JFileChooser();

            int option = fileChooser.showSaveDialog(this);

            if (option == JFileChooser.APPROVE_OPTION) {

                try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()))) {

                    textArea.write(bw);

                } catch (IOException ex) {

                    ex.printStackTrace();

                }

            }

        } else if (e.getSource() == exitApp) {

            System.exit(0);

        }

    }


    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> new SimpleTextEditor());

    }

}



---


Features:


New File → Clears the text area.


Open File → Allows selecting and loading a text file.


Save File → Saves the current text to a file.


Exit → Closes the application 


Controlling a television via Wi‑Fi using Java

 Controlling a television via Wi‑Fi using Java requires:


1. A smart TV or a device like a Chromecast/Fire Stick that exposes a network API.



2. A phone app (Java code on Android or a desktop app) that sends commands via HTTP or socket connection to the TV.





---


Simplified Example (Simulated TV over Wi‑Fi)


This example has two parts:


TV Server (runs on the TV or simulated computer)


Phone Controller (runs on the phone/computer)




---


1. TV Server (Simulated TV)


import java.io.*;

import java.net.*;


public class TVServer {

    private static boolean power = false;

    private static int volume = 10;

    private static int channel = 1;


    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(5000);

        System.out.println("TV Server running on port 5000...");


        while (true) {

            Socket socket = serverSocket.accept();

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            String command = in.readLine();

            System.out.println("Received: " + command);


            switch (command) {

                case "POWER" -> power = !power;

                case "VOL_UP" -> { if (power) volume++; }

                case "VOL_DOWN" -> { if (power && volume > 0) volume--; }

                case "CHANNEL_NEXT" -> { if (power) channel++; }

                case "CHANNEL_PREV" -> { if (power && channel > 1) channel--; }

            }

            System.out.println("Power: " + power + ", Volume: " + volume + ", Channel: " + channel);

            socket.close();

        }

    }

}



---


2. Phone Controller (Client)


import java.io.*;

import java.net.*;

import java.util.Scanner;


public class PhoneControllerWiFi {

    public static void main(String[] args) throws IOException {

        Scanner sc = new Scanner(System.in);

        String serverIP = "192.168.1.5"; // TV's IP address (change to real one)

        int port = 5000;


        while (true) {

            System.out.println("\n--- PHONE REMOTE (Wi-Fi) ---");

            System.out.println("1. Power ON/OFF");

            System.out.println("2. Volume Up");

            System.out.println("3. Volume Down");

            System.out.println("4. Channel Next");

            System.out.println("5. Channel Previous");

            System.out.println("0. Exit");

            System.out.print("Enter choice: ");

            int choice = sc.nextInt();


            String command = switch (choice) {

                case 1 -> "POWER";

                case 2 -> "VOL_UP";

                case 3 -> "VOL_DOWN";

                case 4 -> "CHANNEL_NEXT";

                case 5 -> "CHANNEL_PREV";

                case 0 -> { System.out.println("Exiting..."); return; }

                default -> "INVALID";

            };


            if (!command.equals("INVALID")) {

                try (Socket socket = new Socket(serverIP, port)) {

                    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                    out.println(command);

                }

            }

        }

    }

}



---


How it Works


1. Run TVServer.java on one computer (simulating the TV).



2. Run PhoneControllerWiFi.java on another device connected to the same Wi‑Fi network.



3. Replace "192.168.1.5" with the actual IP address of the computer running TVServer.



4. Commands will be sent via TCP sockets.





---


To Control a Real TV


Many smart TVs (Samsung, LG, Android TV) support HTTP or WebSocket APIs.


You need to use their API docume

ntation to send actual commands.


Example: For an Android TV, you can send HTTP POST requests to http://<TV-IP>:8080/command.




PROFESSIONAL DAILY ACTIVITIES MANAGEMENT APPLICATION

 We'll make a professional daily activities management application using a clickable calendar (date picker) instead of typing the date manually.

For pure Java Swing, we can use JDateChooser from JCalendar (a small open-source library).


---


Steps to Add Date Picker


1. Download JCalendar Library


Get JCalendar.jar and add it to your project classpath.


2. Use JDateChooser instead of a simple text field.


---


Updated Code with Calendar


import com.toedter.calendar.JDateChooser;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.text.SimpleDateFormat;

import java.util.*;

import java.util.List;

import java.util.Timer;

import java.util.TimerTask;


public class DailyActivityCoordinatorCalendar extends JFrame {

    private JTextField activityField, timeField;

    private JDateChooser dateChooser;

    private DefaultListModel<String> activityListModel;

    private List<Activity> activityListData = new ArrayList<>();

    private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");

    private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");


    public DailyActivityCoordinatorCalendar() {

        setTitle("Daily Activity Coordinator with Calendar");

        setSize(500, 350);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setLocationRelativeTo(null);


        // Components

        JLabel activityLabel = new JLabel("Activity:");

        activityField = new JTextField(10);


        JLabel timeLabel = new JLabel("Time (HH:mm):");

        timeField = new JTextField(6);


        JLabel dateLabel = new JLabel("Pick Date:");

        dateChooser = new JDateChooser();

        dateChooser.setDateFormatString("dd-MM-yyyy");


        JButton addButton = new JButton("Add Activity");

        JButton clearButton = new JButton("Clear All");


        activityListModel = new DefaultListModel<>();

        JList<String> activityList = new JList<>(activityListModel);


        // Input panel

        JPanel inputPanel = new JPanel();

        inputPanel.add(activityLabel);

        inputPanel.add(activityField);

        inputPanel.add(timeLabel);

        inputPanel.add(timeField);

        inputPanel.add(dateLabel);

        inputPanel.add(dateChooser);

        inputPanel.add(addButton);

        inputPanel.add(clearButton);


        add(inputPanel, BorderLayout.NORTH);

        add(new JScrollPane(activityList), BorderLayout.CENTER);


        // Button listeners

        addButton.addActionListener(e -> addActivity());

        clearButton.addActionListener(e -> clearActivities());


        // Timer for alarm

        Timer timer = new Timer(true);

        timer.scheduleAtFixedRate(new TimerTask() {

            public void run() {

                checkAlarms();

            }

        }, 0, 60000); // check every minute

    }


    private void addActivity() {

        try {

            String activity = activityField.getText().trim();

            Date selectedDate = dateChooser.getDate();

            Date time = timeFormat.parse(timeField.getText().trim());


            if (!activity.isEmpty() && selectedDate != null) {

                activityListModel.addElement(dateFormat.format(selectedDate) + " " +

                        timeField.getText() + " - " + activity);

                activityListData.add(new Activity(activity, selectedDate, time));

                activityField.setText("");

                timeField.setText("");

            } else {

                JOptionPane.showMessageDialog(this, "Enter activity and pick date!");

            }

        } catch (Exception ex) {

            JOptionPane.showMessageDialog(this, "Invalid time format (HH:mm)");

        }

    }


    private void clearActivities() {

        activityListModel.clear();

        activityListData.clear();

    }


    private void checkAlarms() {

        Date now = new Date();

        String today = dateFormat.format(now);

        String currentTime = timeFormat.format(now);


        for (Activity a : activityListData) {

            if (dateFormat.format(a.date).equals(today) &&

                timeFormat.format(a.time).equals(currentTime)) {

                SwingUtilities.invokeLater(() -> {

                    JOptionPane.showMessageDialog(this,

                            "Reminder: " + a.name + " at " + currentTime);

                });

            }

        }

    }


    class Activity {

        String name;

        Date date;

        Date time;

        Activity(String name, Date date, Date time) {

            this.name = name;

            this.date = date;

            this.time = time;

        }

    }


    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> new DailyActivityCoordinatorCalendar().setVisible(true));

    }

}


Added JDateChooser for a professional date picker.


No need to type date manually anymore.


Rest of the features (alarm notifications, clear, list display) remain.


#followers #highlights

Java Implementation of Iterative Deepening Search

This Java program,Implements Iterative Deepening.Iterative deepening depth-first search(IDDFS) is a state space search strategy in which a depth-limited search is run repeatedly, increasing the depth limit with each iteration until it reaches , the depth of the shallowest goal state. IDDFS is equivalent to breadth-first search, but uses much less memory; on each iteration, it visits the nodes in the search tree in the same order as depth-first search, but the cumulative order in which nodes are first visited is effectively breadth-first.
Here is the source code of the Java program implements iterative deepening. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.
package Search_Algorithm;

/**
 *
 * @author sam
 */
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;

public class DepthLimitedSearch
{
    private Stack<Integer> stack;
    private int numberOfNodes;
    private static final int MAX_DEPTH = 3;

    public DepthLimitedSearch(int numberOfNodes)
    {
        this.numberOfNodes = numberOfNodes;
        this.stack = new Stack<Integer>();
    }

    public void depthLimitedSearch(int adjacencyMatrix[][], int startNode)
    {
        int visited[] = new int[numberOfNodes + 1];
        int element, destination;
        int depth = 0;

        System.out.println(startNode + " at depth " + depth);
        stack.push(startNode);
        visited[startNode] = 1;
        depth = 0;

        while (!stack.isEmpty())
        {
            element = stack.peek();
            destination = element;
            while (destination <= numberOfNodes)
            {
                if (depth < MAX_DEPTH)
                {
                    if (adjacencyMatrix[element][destination] == 1 && visited[destination] == 0)
                    {
                        stack.push(destination);
                        visited[destination] = 1;
                        depth++;
                        System.out.println(destination + " at depth " + depth);
                        element = destination;
                        destination = 1;
                    }
                }
                else
                {
                    return;
                }
                destination++;
            }
            stack.pop();
            depth--;
        }
    }

    public static void main(String... arg)
    {
        int number_of_nodes, startNode;
        Scanner scanner = null;
        try
        {
            System.out.println("Enter the number of nodes in the graph");
            scanner = new Scanner(System.in);
            number_of_nodes = scanner.nextInt();

            int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
            System.out.println("Enter the adjacency matrix");
            for (int i = 1; i <= number_of_nodes; i++)
                for (int j = 1; j <= number_of_nodes; j++)
                    adjacency_matrix[i][j] = scanner.nextInt();

            System.out.println("Enter the startNode for the graph");
            startNode = scanner.nextInt();

            System.out.println("The Depth limited Search Traversal of Max Depth 3 is");
            DepthLimitedSearch depthLimitedSearch = new DepthLimitedSearch(number_of_nodes);
            depthLimitedSearch.depthLimitedSearch(adjacency_matrix, startNode);
 } catch (InputMismatchException inputMismatch)
        { 
            System.out.println("Wrong Input format");
        }
        scanner.close();
    }
}
THE OUTPUT:
Enter the number of nodes in the graph
7
Enter the adjacency matrix
0 1 1 0 0 0 0 
0 0 0 1 1 0 0
0 0 0 0 0 1 1
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
Enter the destination for the graph
7
At Depth 0
1	
At Depth 1
1	2	3	
At Depth 2
1	2	4	5	3	6	7	
Goal Found at depth 2
 

Java Implementation of Depth-limited Search

This Java program,Implements Depth Limited Search.Like the normal depth-first search, depth-limited search is an uninformed search. It works exactly like depth-first search, but avoids its drawbacks regarding completeness by imposing a maximum limit on the depth of the search. Even if the search could still expand a vertex beyond that depth, it will not do so and thereby it will not follow infinitely deep paths or get stuck in cycles. Therefore depth-limited search will find a solution if it is within the depth limit, which guarantees at least completeness on all graphs.
Here is the source code of the Java program to implement depth limited search. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

package Search_Algorithm;

/**
 *
 * @author sam
 */
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;

public class DepthLimitedSearch
{
    private Stack<Integer> stack;
    private int numberOfNodes;
    private static final int MAX_DEPTH = 3;
    public DepthLimitedSearch(int numberOfNodes)
    {
        this.numberOfNodes = numberOfNodes;
        this.stack = new Stack<Integer>();
    }
public void depthLimitedSearch(int adjacencyMatrix[][], int startNode)
    {
        int visited[] = new int[numberOfNodes + 1];
        int element, destination;
        int depth = 0;

        System.out.println(startNode + " at depth " + depth);
        stack.push(startNode);
        visited[startNode] = 1;
        depth = 0;

        while (!stack.isEmpty())
        {
            element = stack.peek();
            destination = element;
            while (destination <= numberOfNodes)
            {
                if (depth < MAX_DEPTH)
                {
                    if (adjacencyMatrix[element][destination] == 1 && visited[destination] == 0)
                    {
                        stack.push(destination);
                        visited[destination] = 1;
                        depth++;
                        System.out.println(destination + " at depth " + depth);
                        element = destination;
                        destination = 1;
                    }
                }
                else
                {
                    return;
                }
                destination++;
            }
            stack.pop();
            depth--;
        }
    }
public static void main(String... arg)
    {
        int number_of_nodes, startNode;
        Scanner scanner = null;
        try
        {
            System.out.println("Enter the number of nodes in the graph");
            scanner = new Scanner(System.in);
            number_of_nodes = scanner.nextInt();

            int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
            System.out.println("Enter the adjacency matrix");
            for (int i = 1; i <= number_of_nodes; i++)
                for (int j = 1; j <= number_of_nodes; j++)
                    adjacency_matrix[i][j] = scanner.nextInt();

            System.out.println("Enter the startNode for the graph");
            startNode = scanner.nextInt();

            System.out.println("The Depth limited Search Traversal of Max Depth 3 is");
            DepthLimitedSearch depthLimitedSearch = new DepthLimitedSearch(number_of_nodes);
            depthLimitedSearch.depthLimitedSearch(adjacency_matrix, startNode);

        } catch (InputMismatchException inputMismatch)
        { 
            System.out.println("Wrong Input format");
        }
        scanner.close();
   }
}
THE OUTPUT:
run:
Enter the number of nodes in the graph
4
Enter the adjacency matrix
0 1 1 0
0 0 1 1
0 0 1 0
1 0 0 1
Enter the startNode for the graph
1
The Depth limited Search Traversal of Max Depth 3 is
1 at depth 0
2 at depth 1
3 at depth 2
4 at depth 2
BUILD SUCCESSFUL (total time: 35 seconds)

Depth First Search Algorithm Java Implementation

Depth First Search (DFS): always expands the deepest node in the current fringe of the search tree. Fringe is a LIFO queue (Stack).
This Java program,performs the DFS traversal on the given graph represented by a adjacency matrix.the DFS traversal makes use of an stack.
Here is the source code of the Java program to perform the dfs traversal. The Java program is successfully compiled and run on a Linux and WIndows system. 

package uninformed;

/**
 *
 * @author sam
 */
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class DFS
{
    private Stack<Integer> stack;
    public DFS() 
    {
        stack = new Stack<Integer>();
    }
    public void dfs(int adjacency_matrix[][], int source)
    {
        int number_of_nodes = adjacency_matrix[source].length - 1;
        int visited[] = new int[number_of_nodes + 1];
        int element = source;
        int i = source, goalnode;
        Scanner scanner = new Scanner(System.in);
        System.out.print("ENTER THE GOAL NODE: ");
        goalnode = scanner.nextInt();
        System.out.print(element + "\t");
        visited[source] = 1;
        stack.push(source);
        while (!stack.isEmpty())
        {
            element = stack.peek();
            i = element;
    while (i <= number_of_nodes)
    {
              if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
        {
                    stack.push(i);
                    visited[i] = 1;
                    element = i;
                    i = 1;
                    System.out.print(element + "\t");
            continue;
                }
                if(i == goalnode) return;
                i++;
    }
            stack.pop();
        }
    }
    public static void main(String...arg)
    {
        int number_of_nodes, source;
        Scanner scanner = null;
  try
        {
    System.out.println("Enter the number of nodes in the graph");
            scanner = new Scanner(System.in);
            number_of_nodes = scanner.nextInt();
    int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
    System.out.println("Enter the adjacency matrix");
    for (int i = 1; i <= number_of_nodes; i++)
        for (int j = 1; j <= number_of_nodes; j++)
                    adjacency_matrix[i][j] = scanner.nextInt();
    System.out.println("Enter the source for the graph");
            source = scanner.nextInt(); 
            System.out.println("The DFS Traversal for the graph is given by \n");
            DFS dfs = new DFS();
            dfs.dfs(adjacency_matrix, source);
        }catch(InputMismatchException inputMismatch)
        {
            System.out.println("Wrong Input format");
        }
        scanner.close();
    }
}

Breadth First Search

Breadth First Search (BFS): is a simple strategy in which the root node is expanded first, then all the successors of the root node are expanded next, then their successors, and so on. Fringe is a FIFO queue.

This Java program, to perform the bfs traversal of a given graph in the form of the adjacency matrix.the bfs traversal makes use of a queue.
Here is the source code of the Java program to perform the BFS traversal. The Java program is successfully compiled and run on a Linux system and Windows also.
package uninformed;

/**
 *
 * @author sam
 */
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class BFS

    private Queue<Integer> queue;

    public BFS()
    {
        queue = new LinkedList<Integer>();
    }

    public void bfs(int adjacency_matrix[][], int source)
    {
        int number_of_nodes = adjacency_matrix[source].length - 1;
        
        
        
        int[] visited = new int[number_of_nodes + 1];
        int i, element, goalnode;
        Scanner scanner = new Scanner(System.in);
        System.out.print("ENTER THE GOAL NODE: ");
        goalnode = scanner.nextInt();
        visited[source] = 1;
        queue.add(source);

        while (!queue.isEmpty())
        {
            element = queue.remove();
            i = element;
            
            System.out.print(i + "\t");
            if(i == goalnode) return;
            while (i <= number_of_nodes)
            {
                if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
                {
                    queue.add(i);
                    visited[i] = 1;
                }
                i++;
            }
        }
        System.out.println();
    }

    public static void main(String... arg)
    {
        int number_no_nodes, source;
        Scanner scanner = null;

        try
        {
            System.out.println("Enter the number of nodes in the graph");
            scanner = new Scanner(System.in);
            number_no_nodes = scanner.nextInt();

            int adjacency_matrix[][] = new int[number_no_nodes + 1][number_no_nodes + 1];
            System.out.println("Enter the adjacency matrix");
            for (int i = 1; i <= number_no_nodes; i++)
                for (int j = 1; j <= number_no_nodes; j++)
                    adjacency_matrix[i][j] = scanner.nextInt();

            System.out.println("Enter the source for the graph");
            source = scanner.nextInt();

            System.out.println("The BFS traversal of the graph is ");
            BFS bfs = new BFS();
            bfs.bfs(adjacency_matrix, source);

        } catch (InputMismatchException inputMismatch)
        {
            System.out.println("Wrong Input Format");
        }
        scanner.close();
    }
}

Facebook