logo
down
shadow

How to adjust graphics on Swing progress indicator?


How to adjust graphics on Swing progress indicator?

By : user2954436
Date : November 22 2020, 01:01 AM
I wish did fix the issue. One problem I see is that the code is setting the composite in the wrong place in the loop. It works, but as you've discovered, it's difficult to maintain or change.
g2.setComposite is being called at the end of the loop. This sets the alpha for the next petal drawn. This means there is no easy change you can make to adjust the alpha of the very first petal.
code :
for (int i = 0; i < 12; i++) {
    float scale = (12 - i) / 12f;
    g2.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, scale * fade));
    g2.drawLine(cx + s, cy, cx + s * 2, cy);
    g2.rotate(-Math.PI / 6, cx, cy);
}
float componentAlpha = 0.5f;

for (int i = 0; i < 12; i++) {
    float scale = (12 - i) / 12f;

    // Give petals the same relative alpha as the component
    // they're overlaying.
    scale *= componentAlpha;   

    g2.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, scale * fade));
    g2.drawLine(cx + s, cy, cx + s * 2, cy);
    g2.rotate(-Math.PI / 6, cx, cy);
}


Share : facebook icon twitter icon
Vaadin progress indicator for displaying Jenkins build progress

Vaadin progress indicator for displaying Jenkins build progress


By : Mihael Milkov
Date : March 29 2020, 07:55 AM
To fix the issue you can do I think you are looking for getEstimatedDuration() implemented by Build class. Or (see the comment there) Executables#getEstimatedDurationFor(Build).
Progress indicator on a form submit targeting an iframe to show load progress in a browser other than IE, i.e. not using

Progress indicator on a form submit targeting an iframe to show load progress in a browser other than IE, i.e. not using


By : Shubhodeep Mitra
Date : March 29 2020, 07:55 AM
Angular HttpClient - show spinner/progress indicator while waiting for service to respond - progress events

Angular HttpClient - show spinner/progress indicator while waiting for service to respond - progress events


By : Yovani Royero
Date : March 29 2020, 07:55 AM
seems to work fine I've combined @aravind answer and this post (https://alligator.io/angular/httpclient-intro/) to piece together a solution. This leverages Angular's Http client progress events to turn the spinner on/off and also handles errors.
component:
code :
showSpinner = false;
this.shortFormService.postShortForm(formModel)
  .subscribe(      

    (event: HttpEvent<any>) => {
      console.log(event)
      switch (event.type) {
        case HttpEventType.Sent:
          this.showSpinner = true;
          console.log('Request sent!');
          break;
        case HttpEventType.ResponseHeader:
          console.log('Response header received!');
          break;
        case HttpEventType.UploadProgress:
          const percentDone = Math.round(100 * event.loaded / event.total);
          console.log(`File is ${percentDone}% uploaded.`);
        case HttpEventType.DownloadProgress:
          const kbLoaded = Math.round(event.loaded / 1024);
          console.log(`Download in progress! ${ kbLoaded }Kb loaded`);
          break;
        case HttpEventType.Response:
          console.log(' Done!', event.body);
          this.showSpinner = false;            

      }
    },
    (err: HttpErrorResponse) => {
      if (err.error instanceof Error) {
        console.log("Client-side error occured.");
      } else {
        this.router.navigate(['/error', err.error.error]);
        console.log("Server-side error occured.");
      }
    }
  )

}
postShortForm(shortForm: any) {
 const req = new HttpRequest('POST', this.preCheckUrl, shortForm, {
  reportProgress: true,
});
return this.httpNew.request(req)
  .retry(3)
}
How to update a JavaFX progress indicator based on progress of separate classes?

How to update a JavaFX progress indicator based on progress of separate classes?


By : Rajneesh Sharma
Date : March 29 2020, 07:55 AM
Does that help You do it by binding progressbar's progress property to two progress properties :
code :
import java.util.concurrent.TimeUnit;
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class TwoLongProcessWithOneProgressBar extends Application {

    @Override
    public void start(Stage stage) throws InterruptedException {

        BorderPane mainPane = new BorderPane();

        FlowPane topPane = new FlowPane(Orientation.HORIZONTAL, 5.,5.);
        topPane.setPadding(new Insets(20.));

        Panel panel = new Panel();
        BorderPane.setAlignment(panel, Pos.CENTER);

        Button button = new Button("Start");
        button.setDefaultButton(true);
        button.setOnAction(e -> {
            panel.runLlongTask();
            button.setDisable(true);
        });
        topPane.getChildren().add(button);
        mainPane.setTop(topPane);

        mainPane.setCenter(panel);
        mainPane.setBottom(panel.getBar());

        Scene scene = new Scene(mainPane, Color.WHITE);
        stage.setScene(scene);
        stage.centerOnScreen();
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

class Panel extends HBox{

    private final ProgressBar bar;

    Panel(){
        setPrefSize(150,50);
        bar = new ProgressBar();
        bar.prefWidthProperty().bind(widthProperty());
    }

    void runLlongTask() {
        Task task1 = new Task1();
        Thread th1 = new Thread(task1);
        th1.setDaemon(true);

        Task task2 = new Task2();
        Thread th2 = new Thread(task2);
        th2.setDaemon(true);
        //bind progress bar to both task progress property
        bar.progressProperty().bind(task1.progressProperty().add(task2.progressProperty()));
        th1.start();
        th2.start();
    }

    ProgressBar getBar() {  return bar; }
}

class Task1 extends Task<Void>{
    @Override
    protected Void call() throws Exception {
        for (int i =0; i<1000; i++) {
            TimeUnit.MILLISECONDS.sleep(100);
            updateProgress(i,2000);
        }
        return null;
    }
}

class Task2 extends Task<Void>{
    @Override
    protected Void call() throws Exception {
        for (int i =0; i<1000; i++) {
            TimeUnit.MILLISECONDS.sleep(100);
            updateProgress(i,2000);
        }
        return null;
    }
}
Javafx Progress-Indicator doesn't show up when I set Progress-Indicator.setVisible(true)

Javafx Progress-Indicator doesn't show up when I set Progress-Indicator.setVisible(true)


By : aww
Date : March 29 2020, 07:55 AM
it should still fix some issue The problem is, that the execution of the apply method blocks the FX-Thread, so the progress indicator can't be displayed.
So the execution needs to be done in another Thread (or a Task) to make the progress indicator visible. Then when the Task has succeeded you can set the visibility of the progress indicator to false again. (Also a problem is that the apply method is just to fast, so the indicator doesn't show up. I added a sleep of 10 seconds to show it's working)
code :
@FXML
private void apply() {
    loading.setVisible(true);

    Task<Void> applyTask = new Task<Void>() {

        @Override
        protected Void call() throws Exception {

            Thread.sleep(10000);//sleep for 10 seconds just to show that the progress indicator is working

            directory = Paths.get(pathField.getText()).toFile();
            if (directory != null) {
                //fx-parts need to be executed by Platform.runLater(...)
                Platform.runLater(() -> pieChartData.clear());

                String strings = new String(pathField.getText());
                calc.calcSubfoldersSize(strings);

                //again let fx-parts be executed in the fx-application-thread
                Platform.runLater(() -> updataLabads());
            }

            return null;
        }
    };

    applyTask.setOnSucceeded(e -> loading.setVisible(false));
    applyTask.setOnFailed(e -> loading.setVisible(false));//handle error here...

    new Thread(applyTask, "Apply thread").start();

    //loading.setVisible(false); //done when the task ends
}
package sample;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.chart.PieChart;

public class Calc {

    private int totalFolder = 0, totalFile = 0;
    private static int counter = 0;
    private final ObservableList<PieChart.Data> pieChartData;
    private ArrayList<PieChart.Data> pieChartData2;//EDIT: here you don't need an ObservableList, a simple ArrayList will do it
    private long filesInRoot = 0;
    Path fileInRoot;

    //added a constructor to receive a reference of the Observable list
    public Calc(ObservableList<PieChart.Data> pieChartData) {
        this.pieChartData = pieChartData;//EDIT: when you set this.pieChartData = pieChartData2 the parameter would be ignored...
        pieChartData2 = new ArrayList<PieChart.Data>();
    }

    public void calcSubfoldersSize(String sPath) { //replaces public void main(String args)
        File nativeFile = new File(sPath);
        File file = new File(nativeFile.toString());

        String[] files = file.list();
        Path path;

        filesInRoot = 0;
        if (file.isDirectory()) {
            for (int i = 0; i <= files.length - 1; i++) {
                path = Paths.get(files[i]);
                file = path.toFile();
                counter++;
            }

            String[] paths = new String[counter];
            for (int i = 0; i <= files.length - 1; i++) {
                path = Paths.get(files[i]);
                file = path.toFile();
                paths[i] = file.toString();
            }

            for (int i = 0; i != counter; i++) {

            }
            for (int i = 0; i + 1 <= paths.length; i++) {
                try {
                    Calc size = new Calc(pieChartData); //the only line changed in the method
                    long fileSizeByte = size.getFileSize(new File(nativeFile.toString() + "\\" + paths[i]));
                    add(paths[i], fileSizeByte, i, paths.length);
                }
                catch (Exception e) {
                    fileInRoot = Paths.get(nativeFile.toString() + "\\" + paths[i]);
                    filesInRoot = filesInRoot + fileInRoot.toFile().length();
                }
            }
            if (filesInRoot != 0) {
                add("Files in Directory", filesInRoot, 1, 100);
                pieChartData2.add(new PieChart.Data("Files in Directory", filesInRoot));
                System.out.println(filesInRoot);
            }
        }

        //EDIT: let this part be executed by the fx-application thread:
        Platform.runLater(() -> pieChartData.addAll(pieChartData2));
    }

    //let add update the observable list
    public void add(String loc, long size, int i, int aim) {
        pieChartData2.add(new PieChart.Data(loc, size));//EDIT: the error seems to occur here because pieChartData2 was null (but I'm not sure why there was no exception shown...; probably because it's executed in the task...) 
    }

    public long getFileSize(File folder) {
        long foldersize = 0;

        totalFolder++;
        //          System.out.println("Folder: " + folder + "  (Source: getFileSize)");
        File[] filelist = folder.listFiles();
        //          System.out.println(folder.listFiles());

        for (int i = 0; i < filelist.length; i++) {
            if (filelist[i].isDirectory()) {
                foldersize += getFileSize(filelist[i]);
            }
            else {
                totalFile++;
                foldersize += filelist[i].length();
            }
        }

        return foldersize;

    }

    public int getTotalFolder() {
        return totalFolder;
    }

    public int getTotalFile() {
        return totalFile;
    }
}
//...
String strings = new String(pathField.getText());
calc.calcSubfoldersSize(strings);
Platform.runLater(() -> initialize());
//...
package sample;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Controller {

    @FXML
    private PieChart pieChart;
    @FXML
    private TextField pathField;
    @FXML
    private Label subfolder;
    @FXML
    private Button up;
    @FXML
    private Button hide;
    @FXML
    private Button showHidden;
    @FXML
    private VBox field1;
    @FXML
    private VBox field2;
    @FXML
    private VBox field3;
    @FXML
    private VBox field4;
    @FXML
    private AnchorPane parentContainer;
    @FXML
    private ProgressIndicator loading;

    private ObservableList<PieChart.Data> pieChartData;
    private Calc calc;
    public File directory;
    String[] unit = {"Bytes", "KB", "MB", "GB", "TB", "PB", "ZB", "EB"};
    int units = 0;
    boolean hideSegment = false;
    String[] hiddenPath = new String[500];
    double[] hiddenSize = new double[500];
    int Stelle = 499;
    boolean first = true;

    @FXML
    void initialize() {
        pieChartData = FXCollections.observableArrayList();
        calc = new Calc(pieChartData);
        updataLabads();
        pieChart.setData(pieChartData);
    }

    @FXML
    private void handleBrowse() {
        Stage stage = new Stage();
        final DirectoryChooser dirChooser = new DirectoryChooser();
        directory = dirChooser.showDialog(stage);
        if (directory != null) {
            pathField.setText(directory.toString());
        }
    }

    @FXML
    private void apply() {
        loading.setVisible(true);

        Task<Void> applyTask = new Task<Void>() {

            @Override
            protected Void call() throws Exception {

                Thread.sleep(3000);//sleep for 3 seconds just to show that the progress indicator is working

                directory = Paths.get(pathField.getText()).toFile();
                if (directory != null) {
                    //fx-parts need to be executed by Platform.runLater(...)
                    Platform.runLater(() -> pieChartData.clear());

                    String strings = new String(pathField.getText());
                    calc.calcSubfoldersSize(strings);

                    //again let fx-parts be executed in the fx-application-thread
                    Platform.runLater(() -> updataLabads());
                }

                return null;
            }
        };

        applyTask.setOnSucceeded(e -> loading.setVisible(false));
        applyTask.setOnFailed(e -> loading.setVisible(false));//handle error here...

        new Thread(applyTask, "Apply thread").start();

        //loading.setVisible(false); //done when the task ends
    }

    public void updataLabads() {
        pieChart.getData().forEach(data -> {
            data.getNode().addEventHandler(MouseEvent.MOUSE_ENTERED, e -> {

                for (int i = 0; (data.getPieValue() / (Math.pow(1024, i))) > 1000; i++) {
                    //System.out.println(i);
                    units = i + 1;
                }
                subfolder.setText(data.getName() + ", " + Math.round(data.getPieValue() / (Math.pow(1024, units))) + " " + unit[units]);
                //System.out.println(Math.round(data.getPieValue()/(Math.pow(1024,units))) + " " + unit[units]);
            });
        });
        pieChart.getData().forEach(data -> {
            data.getNode().addEventHandler(MouseEvent.MOUSE_RELEASED, e -> {
                if (hideSegment == false) {
                    pathField.setText(pathField.getText() + "\\" + data.getName());
                    apply();
                }
                else if (hideSegment == true) {
                    pieChartData.remove(data);
                    hideSegment = false;
                    if (first == true) {
                        first = false;
                        Stelle = 0;
                    }
                    hiddenPath[Stelle] = data.getName();
                    hiddenSize[Stelle] = data.getPieValue();
                    System.out.println("Hidden Variables have been updatet on Port " + Stelle);
                    Stelle++;
                    pieChart.setData(pieChartData);
                }
            });
        });
    }

    @FXML
    private void up() {
        while (!pathField.getText().substring(pathField.getText().length() - 1).equals("\\")) {
            pathField.setText(pathField.getText().substring(0, pathField.getText().length() - 1));
        }
        pathField.setText(pathField.getText().substring(0, pathField.getText().length() - 1));
        apply();
    }

    @FXML
    public void hide() {
        if (hideSegment == false)
            hideSegment = true;
        else if (hideSegment == true)
            hideSegment = false;
    }

    @FXML
    public void showHidden() {
        System.out.println("Tried to load HiddenVariables on Port " + (Stelle - 1));
        System.out.println(hiddenPath[Stelle - 1] + "   " + hiddenSize[Stelle - 1]);
        if (!hiddenPath[Stelle - 1].equals(null)) {
            for (int i = Stelle; i != 0; i--) {
                pieChartData.add(new PieChart.Data(hiddenPath[Stelle - 1], hiddenSize[Stelle - 1]));
                hiddenPath[Stelle - 1] = "";
                hiddenSize[Stelle - 1] = 0;
                Stelle--;
                pieChart.setData(pieChartData);
                updataLabads();
            }
        }
    }

    @FXML
    public void Home() throws IOException {
        Parent root = FXMLLoader.load(getClass().getResource("Home.fxml"));
        Scene scene = up.getScene();
        root.translateYProperty().set(scene.getHeight());
        parentContainer.getChildren().add(root);
        Timeline timeline = new Timeline();
        KeyValue kv = new KeyValue(root.translateYProperty(), 0, Interpolator.EASE_BOTH);
        KeyFrame kf = new KeyFrame(Duration.seconds(.5), kv);
        timeline.getKeyFrames().add(kf);
        timeline.play();
        parentContainer.getChildren().remove(parentContainer);
    }

    @FXML
    public void Files() {}

    @FXML
    public void Settings() {}

    @FXML
    public void Close() {
        Platform.exit();
    }
}
Related Posts Related Posts :
  • Why is it mandatory for ternary operations to return a value?
  • How can I make my listview rows different heights
  • Array declaration trick : Is it bad to use it?
  • Calling different classes with if else statements
  • Free API for speech recognition system
  • Java: Objects in JFrame are messed up
  • Is there a similar of MessageBox of ExtJS in ADF Faces
  • Passing HttpServletResponse in Spring Boot controller method
  • Failed to load libraries: [netty_tcnative_linux_arm_32, netty_tcnative_linux_arm_32_fedora, netty_tcnative_arm_32, netty
  • How to build a small documents storage?
  • Getting pixel position of a text in an image
  • How do I get a list of Methods called from a Class in Eclipse IDE?
  • Convert string to day of week (not exact date)
  • Unable to understand how rounding is working for decimal digits (Java)
  • How to avoid java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.copy(Ljava/io/InputStream;Ljava/io/OutputStream;)
  • JTable Renderer not working with RowSorter?
  • From java.util.concurrent.Future<T> to play.libs.F.Promise<T>: How to do that in Java?
  • jUnit tests work in Eclipse, but fail in ant - java.lang.RuntimeException: Stub
  • How do i add a tooltip to existing gwt Textbox?
  • actor replying to non-actor
  • Google Cloud Messaging - server connection
  • Which classes are unmodifiable and cannot be intrumented and is there a way to bypass it?
  • Java & Jersey 1.17: Custom default response headers
  • Java rounding error
  • Setting custom RejectedExecutionHandler for ThreadPoolExecutor after executing some tasks?
  • Arquillian test class variables lose value
  • java.util.ConcurrentModificationException while inserting in ArrayList
  • How to write generic Java API without method Overloading
  • Java Serialization / Deserialization of an ArrayList works only on first program execution
  • Conway's Game of Life's rules dont apply properly
  • call a java method when Click on a html button without using javascript
  • Why does SSLSocketFactory.createSocket returns a Socket instead of SSLSocket?
  • How to schedule a task in Tomcat
  • compare two pdf files (approach) using java
  • What is the use of allowCoreThreadTimeout( ) in ThreadPoolExecutor?
  • Describe the Strategy Design Pattern in Java?
  • MongoDB too many open connections
  • Issue with generate JAXB classes with value constructors
  • Moving from one frame to another in java swing
  • Get a thread by Id
  • how to open front camera and back camera at same time?
  • Messed up with Java Declaration
  • Extracting chart in EXcel as image using java
  • How to get latitude and longitude in Android phone?
  • Do GC pauses and kill -STOP produce the same behavior?
  • Android HTML.ImageGetter Images resized
  • The way to instantiate map<String, List<String>> in Java
  • Java Making objects move while buttons held
  • Androidx Navigation View - `setNavigationItemSelectedListener` Doesn't Work
  • after compiling code JFrame does not appear
  • Netbeans project, JFrames ran from the main JFrame close all JFrames in project
  • Square Retrofit Client: How to enable/disable followRedirects? How to intercept redirect URL?
  • Java Circular Reference - Can’t Compile
  • Mouse click on specific time JAVA
  • android 4 onCreateDialog return type incompatible when overriding
  • Java Implementation of Oracle's DBMS_UTILITY.GET_HASH_VALUE Function
  • javac cannot be run, and furthermore does not seem installed
  • Function to obtain a thread given its ID
  • Java File path to Executable has spaces
  • Minimum Oracle Java VM heap memory setting?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org