2012-12-27 7 views
7

Ich habe vor kurzem begonnen, mit JavaFX zu arbeiten, und fing an, FX-Versionen meiner eigenen Swing-Komponenten zu machen. Einer von ihnen war ein Countdown-Timer, in dem eine JProgressBar beteiligt war. Ich würde die aktuelle Zeit mit der Methode setString(String) auf die Leiste zeichnen. Leider scheint eine solche Methode mit JavaFX ProgressBar nicht zu sein. Das nächste, was ich zu sah, was ich suchte, war dies:Zeichne einen String auf eine ProgressBar, wie zB JProgressBar?

timer (source)

Ich weiß nicht, ob dies eine ganz neue benutzerdefinierte Komponente erfordern würde, oder einfach nur eine Klasse wie java.awt.Graphics.

Jede Hilfe würde sehr geschätzt werden. Danke :)

Antwort

12

Hier ist ein Beispiel, das (ich denke) tut, was Ihre Frage fragt.

class ProgressIndicatorBar extends StackPane { 
    final private ReadOnlyDoubleProperty workDone; 
    final private double totalWork; 

    final private ProgressBar bar = new ProgressBar(); 
    final private Text  text = new Text(); 
    final private String  labelFormatSpecifier; 

    final private static int DEFAULT_LABEL_PADDING = 5; 

    ProgressIndicatorBar(final ReadOnlyDoubleProperty workDone, final double totalWork, final String labelFormatSpecifier) { 
    this.workDone = workDone; 
    this.totalWork = totalWork; 
    this.labelFormatSpecifier = labelFormatSpecifier; 

    syncProgress(); 
    workDone.addListener(new ChangeListener<Number>() { 
     @Override public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) { 
     syncProgress(); 
     } 
    }); 

    bar.setMaxWidth(Double.MAX_VALUE); // allows the progress bar to expand to fill available horizontal space. 

    getChildren().setAll(bar, text); 
    } 

    // synchronizes the progress indicated with the work done. 
    private void syncProgress() { 
    if (workDone == null || totalWork == 0) { 
     text.setText(""); 
     bar.setProgress(ProgressBar.INDETERMINATE_PROGRESS); 
    } else { 
     text.setText(String.format(labelFormatSpecifier, Math.ceil(workDone.get()))); 
     bar.setProgress(workDone.get()/totalWork); 
    } 

    bar.setMinHeight(text.getBoundsInLocal().getHeight() + DEFAULT_LABEL_PADDING * 2); 
    bar.setMinWidth (text.getBoundsInLocal().getWidth() + DEFAULT_LABEL_PADDING * 2); 
    } 
} 

Ein complete executable test harness ist ebenfalls verfügbar.

Beispielprogramm Ausgabe:

labeledprogressbar

+0

Das ist genau das, was ich suchte. Vielen Dank :) – mattbdean