/*
 * Copyright (c) 2024. Elex. All Rights Reesrved.
 * https://www.elex-project.com/
 */

package com.elex_project.examples.components.progress;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class ProgressBarExample extends JPanel {
	final JProgressBar progressBar;

	public ProgressBarExample() {
		super();
		setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

		final JButton button = new JButton("Start");
		progressBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
		progressBar.setIndeterminate(false);
		progressBar.setStringPainted(true);

		this.add(button);
		this.add(progressBar);

		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				Task task = new Task();
				task.execute();
			}
		});
	}

	public class Task extends SwingWorker<Integer, Integer> {

		@Override
		protected Integer doInBackground() throws Exception {
			int i = 0;
			while (i < 100) {
				Thread.sleep(100);
				i++;

				progressBar.setValue(i);
				publish(i);
			}
			return 100;
		}

		@Override
		protected void done() {
			progressBar.setValue(100);
			progressBar.setString("Done!");
		}
	}

	public static void main(String... args) {

		final JFrame jFrame = new JFrame();
		jFrame.setTitle("Example");
		jFrame.setSize(800, 600);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.setContentPane(new ProgressBarExample());

		SwingUtilities.invokeLater(() -> {
			jFrame.setVisible(true);
		});


	}
}
