2012-12-27 21 views
7

我最近開始使用JavaFX,並開始製作自定義Swing組件的FX版本。其中之一是倒數計時器,其中涉及JProgressBar。我會使用它的setString(String)方法將當前時間繪製到酒吧上。不幸的是,JavaFX的ProgressBar似乎沒有這種方法。我看到了什麼,我一直在尋找最接近的事是這樣的:在ProgressBar上繪製一個字符串,如JProgressBar?

timersource

我不知道這是否會需要一個全新的自定義組件,或者只是像java.awt.Graphics類。

任何幫助將不勝感激。謝謝:)

回答

12

這是一個示例(我認爲)做你的問題是什麼問。

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); 
    } 
} 

A complete executable test harness也可用。

示例程序輸出:

labeledprogressbar

+0

這正是我一直在尋找。謝謝 :) – mattbdean

相關問題