Saturday, May 31, 2025

[JAVA] SPEEDTEST NETWORK

long download1 = net.getBytesRecv();
long timestamp1 = net.getTimeStamp();
Thread.sleep(2000); //Sleep for a bit longer, 2s should cover almost every possible problem
net.updateNetworkStats(); //Updating network stats
long download2 = net.getBytesRecv();
long timestamp2 = net.getTimeStamp();
System.out.println("prova " + (download2 - download1)/(timestamp2 - timestamp1));
//Do the correct calculations

[JAVA] SERVER CLIENT NETWORK

// Server.java
import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(12345);
        Socket clientSocket = serverSocket.accept();
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println("Received: " + inputLine);
            out.println("Server received: " + inputLine);
        }
    }
}

// Client.java
import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 12345);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out.println("Hello from client");
        System.out.println("Server response: " + in.readLine());
    }
}

[JAVA] FILL COLOUR from MOUSE

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

public class ColorFromMouse extends JPanel {

    private Color selectedColor = Color.BLACK;
    private int regionWidth = 50; // Example region width

    public ColorFromMouse() {
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int x = e.getX();
                int region = x / regionWidth;

                // Example mapping of regions to colors
                switch (region) {
                    case 0: selectedColor = Color.RED; break;
                    case 1: selectedColor = Color.GREEN; break;
                    case 2: selectedColor = Color.BLUE; break;
                    default: selectedColor = Color.BLACK;
                }
                repaint(); // Trigger redraw with the new color
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(selectedColor);
        g.fillRect(50, 50, 100, 100); // Example filled rectangle
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Color From Mouse");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ColorFromMouse());
        frame.setSize(300, 300);
        frame.setVisible(true);
    }
}

[JAVA] DOWNLOAD DATA FROM PROCESS

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class Progressbar {

    public static void main(String[] args) {

        final JProgressBar jProgressBar = new JProgressBar();
        jProgressBar.setMaximum(100000);
        JFrame frame = new JFrame();
        frame.setContentPane(jProgressBar);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(300, 70);
        frame.setVisible(true);

        Runnable updatethread = new Runnable() {
            public void run() {
                try {

                    URL url = new URL("http://downloads.sourceforge.net/project/bitcoin/Bitcoin/blockchain/bitcoin_blockchain_170000.zip");
                    HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
                    long completeFileSize = httpConnection.getContentLength();

                    java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
                    java.io.FileOutputStream fos = new java.io.FileOutputStream(
                            "package.zip");
                    java.io.BufferedOutputStream bout = new BufferedOutputStream(
                            fos, 1024);
                    byte[] data = new byte[1024];
                    long downloadedFileSize = 0;
                    int x = 0;
                    while ((x = in.read(data, 0, 1024)) >= 0) {
                        downloadedFileSize += x;

                        // calculate progress
                        final int currentProgress = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 100000d);

                        // update progress bar
                        SwingUtilities.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                jProgressBar.setValue(currentProgress);
                            }
                        });

                        bout.write(data, 0, x);
                    }
                    bout.close();
                    in.close();
                } catch (FileNotFoundException e) {
                } catch (IOException e) {
                }
            }
        };
        new Thread(updatethread).

        start();
    }

}

[JAVA] PROCESS BAR

public class ProgressBar {
    public static void main(String[] args) throws InterruptedException {
        int total = 100;
        for (int i = 0; i <= total; i++) {
            String bar = generateProgressBar(i, total);
            System.out.print("\r" + bar + " " + i + "%");
            Thread.sleep(50);
        }
        System.out.println();
    }

    private static String generateProgressBar(int current, int total) {
        int progressBarLength = 30;
        int filledLength = (int) (progressBarLength * ((double) current / total));
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < progressBarLength; i++) {
            if (i < filledLength) {
                sb.append("=");
            } else {
                sb.append(" ");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}

[JAVA] OPEN FILE TO TEXTAREA

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

public class FileToTextArea extends JFrame {

    private JTextArea textArea;

    public FileToTextArea() {
        setTitle("File to TextArea");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        add(scrollPane, BorderLayout.CENTER);

        JButton openButton = new JButton("Open File");
        openButton.addActionListener(e -> openFile());
        add(openButton, BorderLayout.SOUTH);

        setVisible(true);
    }

    private void openFile() {
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showOpenDialog(this);

        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
                textArea.setText(""); // Clear existing text
                String line;
                while ((line = reader.readLine()) != null) {
                    textArea.append(line + "\n");
                }
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "Error reading file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(FileToTextArea::new);
    }
}

[JAVA] CREATE FILE FROM TEXTAREA

import javax.swing.*;import java.io.*;public class TextAreaToFile { public static void main(String[] args) { JFrame frame = new JFrame("Text Area to File"); JTextArea textArea = new JTextArea("Enter text here."); JButton saveButton = new JButton("Save to File"); saveButton.addActionListener(e -> { String text = textArea.getText(); File file = new File("output.txt"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { writer.write(text); JOptionPane.showMessageDialog(frame, "File saved successfully!"); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(frame, "Error saving file.", "Error", JOptionPane.ERROR_MESSAGE); } }); JPanel panel = new JPanel(); panel.add(new JScrollPane(textArea)); panel.add(saveButton); frame.add(panel); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}