Tuesday, July 22, 2025

Java Limit Downloader

# Java Swing Download Manager with Progress Bar and Time Limit

Here's a complete implementation of a download manager with:
- JProgressBar to show download progress
- Countdown timer for download time limit
- Ability to pause/resume downloads
- Visual feedback for time remaining

```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

public class DownloadManager extends JFrame {
    private JProgressBar progressBar;
    private JButton downloadButton, pauseButton;
    private JLabel statusLabel, timeRemainingLabel;
    private JTextField urlField;
    private Timer countdownTimer;
    private int timeLimitSeconds = 60; // 1 minute time limit
    private AtomicBoolean isPaused = new AtomicBoolean(false);
    private AtomicBoolean isDownloading = new AtomicBoolean(false);
    private AtomicLong downloadedBytes = new AtomicLong(0);
    private long totalBytes;

    public DownloadManager() {
        setTitle("Download Manager with Time Limit");
        setSize(600, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout(10, 10));

        // Create components
        urlField = new JTextField("https://example.com/largefile.zip");
        downloadButton = new JButton("Start Download");
        pauseButton = new JButton("Pause");
        pauseButton.setEnabled(false);
        progressBar = new JProgressBar(0, 100);
        statusLabel = new JLabel("Ready to download");
        timeRemainingLabel = new JLabel("Time remaining: --:--");

        // Add action listeners
        downloadButton.addActionListener(e -> startDownload());
        pauseButton.addActionListener(e -> togglePause());

        // Create panels
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.add(new JLabel("Download URL:"), BorderLayout.WEST);
        inputPanel.add(urlField, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(downloadButton);
        buttonPanel.add(pauseButton);

        JPanel infoPanel = new JPanel(new GridLayout(2, 1));
        infoPanel.add(statusLabel);
        infoPanel.add(timeRemainingLabel);

        // Add components to frame
        add(inputPanel, BorderLayout.NORTH);
        add(progressBar, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
        add(infoPanel, BorderLayout.EAST);

        // Initialize countdown timer (but don't start it yet)
        countdownTimer = new Timer(1000, e -> updateCountdown());
    }

    private void startDownload() {
        if (isDownloading.get()) {
            JOptionPane.showMessageDialog(this, "Download already in progress");
            return;
        }

        String url = urlField.getText().trim();
        if (url.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please enter a URL");
            return;
        }

        new Thread(() -> {
            try {
                isDownloading.set(true);
                downloadedBytes.set(0);
                SwingUtilities.invokeLater(() -> {
                    downloadButton.setEnabled(false);
                    pauseButton.setEnabled(true);
                    statusLabel.setText("Downloading...");
                    timeRemainingLabel.setText("Time remaining: " + formatTime(timeLimitSeconds));
                });

                URL downloadUrl = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection();
                totalBytes = connection.getContentLengthLong();

                // Start countdown timer
                countdownTimer.start();

                try (InputStream in = connection.getInputStream();
                     FileOutputStream out = new FileOutputStream("downloaded_file.tmp")) {

                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    long startTime = System.currentTimeMillis();

                    while ((bytesRead = in.read(buffer)) != -1 && !isPaused.get() && timeLimitSeconds > 0) {
                        out.write(buffer, 0, bytesRead);
                        downloadedBytes.addAndGet(bytesRead);

                        // Calculate progress
                        int progress = (int) (downloadedBytes.get() * 100 / totalBytes);
                        long elapsedTime = System.currentTimeMillis() - startTime;
                        long estimatedTotalTime = (elapsedTime * totalBytes) / downloadedBytes.get();
                        long remainingTime = estimatedTotalTime - elapsedTime;

                        SwingUtilities.invokeLater(() -> {
                            progressBar.setValue(progress);
                            statusLabel.setText(String.format("Downloaded: %d/%d KB", 
                                downloadedBytes.get()/1024, totalBytes/1024));
                        });
                    }

                    if (timeLimitSeconds <= 0) {
                        SwingUtilities.invokeLater(() -> {
                            statusLabel.setText("Download timed out!");
                            progressBar.setValue(0);
                        });
                    } else if (isPaused.get()) {
                        SwingUtilities.invokeLater(() -> statusLabel.setText("Download paused"));
                    } else {
                        SwingUtilities.invokeLater(() -> statusLabel.setText("Download complete!"));
                    }
                }
            } catch (Exception ex) {
                SwingUtilities.invokeLater(() -> {
                    statusLabel.setText("Error: " + ex.getMessage());
                    progressBar.setValue(0);
                });
                ex.printStackTrace();
            } finally {
                isDownloading.set(false);
                isPaused.set(false);
                countdownTimer.stop();
                SwingUtilities.invokeLater(() -> {
                    downloadButton.setEnabled(true);
                    pauseButton.setEnabled(false);
                    pauseButton.setText("Pause");
                });
            }
        }).start();
    }

    private void togglePause() {
        if (isPaused.get()) {
            isPaused.set(false);
            pauseButton.setText("Pause");
            statusLabel.setText("Resuming download...");
            startDownload(); // Resume download
        } else {
            isPaused.set(true);
            pauseButton.setText("Resume");
            statusLabel.setText("Download paused");
        }
    }

    private void updateCountdown() {
        timeLimitSeconds--;
        SwingUtilities.invokeLater(() -> {
            timeRemainingLabel.setText("Time remaining: " + formatTime(timeLimitSeconds));
        });

        if (timeLimitSeconds <= 0) {
            countdownTimer.stop();
            isPaused.set(true);
            SwingUtilities.invokeLater(() -> {
                statusLabel.setText("Time limit reached!");
                pauseButton.setEnabled(false);
            });
        }
    }

    private String formatTime(int totalSeconds) {
        int minutes = totalSeconds / 60;
        int seconds = totalSeconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            DownloadManager manager = new DownloadManager();
            manager.setVisible(true);
        });
    }
}
```

## Key Features

1. **Download Progress Tracking**:
   - JProgressBar shows real-time download progress
   - Displays downloaded/total file size
   - Calculates and shows remaining time estimate

2. **Time Limit Functionality**:
   - Countdown timer (default 60 seconds)
   - Visual countdown display
   - Automatic pause when time limit is reached

3. **Download Control**:
   - Start/stop download functionality
   - Pause/resume capability
   - Error handling for network issues

4. **User Interface**:
   - Clean Swing interface
   - Real-time status updates
   - Visual feedback for all operations

## How to Use

1. Enter a valid download URL in the text field
2. Click "Start Download" to begin
3. Use the "Pause" button to pause/resume
4. The progress bar will show download completion
5. The countdown timer will show remaining time

## Customization Options

1. **Change Time Limit**:
   ```java
   private int timeLimitSeconds = 120; // 2 minutes
   ```

2. **Add Speed Calculation**:
   ```java
   // Add to download loop
   long speed = (downloadedBytes.get() * 1000) / (elapsedTime + 1); // bytes/sec
   statusLabel.setText(String.format("%.1f KB/s", speed/1024.0));
   ```

3. **Add File Save Dialog**:
   ```java
   JFileChooser fileChooser = new JFileChooser();
   if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
       File outputFile = fileChooser.getSelectedFile();
       // Use this file in your FileOutputStream
   }
   ```

4. **Add Multiple Downloads**:
   You could extend this to handle a download queue with multiple files

Would you like me to explain any specific part in more detail or add additional features to this implementation?

No comments: