2017-02-24 97 views
2

私はjavafxで新しく、カスタムダイアログ/アラートを作成しようとしていました。私はシーンビルダを使用してGUIを設計していますが、fxmlファイルをロードするたびに(つまりタイトル、ラベルテキストなどを変更する)ダイアログを変更したいので、パラメータを送信してステージ/シーンを変更する方法、またはこれを達成できる方法です。JavaFX - fxmlを使ってカスタムダイアログを作成

具体的には、私のプログラムのどこででも処理したいエラーがあるとしましょう。作成したエラーダイアログを表す新しいfxmlファイルを読み込み、タイプに応じてコンポーネントを変更しますスイングでJOptionPane.showMessageDialog(...)と同様に、処理する必要があるエラーです。

+0

なぜ['Alert']を使用するだけではありません(http://docs.oracle.co m/javase/8/javafx/api/javafx/scene/control/Alert.html)または['Dialog'](http://docs.oracle.com/javase/8/javafx/api/javafx/scene/control /Dialog.html)? –

+0

James_D、私はすべての異なったデザインが必要で、またすべての情報は別の言語(英語ではない)でなければなりません – Askiin

+0

彼らはそれを行うことができますか、確かに、もっと一般的な質問に答える答えを追加します。 –

答えて

3

あなたが説明したユースケースについては、Dialog API、またはそれに含まれる特殊なAlertクラスを使用できます。

あなたが尋ねるより一般的な質問については

:私はこれを行う方法が使用するパラメータを送信し、ステージ/シーンに

を変更する方法はありますかどうかを知りたかった

custom componentメカニズムを説明しています。要するに、FXMLファイルをロードするために必要なUIタイプのサブクラスを作成し、必要なプロパティを定義します。たとえば、次のようにします。

public class ExceptionPane extends BorderPane { 

    private final ObjectProperty<Exception> exception ; 

    public ObjectProperty<Exception> exceptionProperty() { 
     return exception ; 
    } 

    public final Exception getException() { 
     return exceptionProperty().get(); 
    } 

    public final void setException(Exception exception) { 
     exceptionProperty().set(exception); 
    } 

    @FXML 
    private final TextArea stackTrace ; 
    @FXML 
    private final Label message ; 

    public ExceptionPane() throws Exception { 

     FXMLLoader loader = new FXMLLoader(getClass().getResource("path/to/fxml")); 
     loader.setRoot(this); 
     loader.setController(this); 

     loader.load(); 

     exception.addListener((obs, oldException, newException) -> { 
      if (newException == null) { 
       message.setText(null); 
       stackTrace.setText(null); 
      } else { 
       message.setText(newException.getMessage()); 
       StringWriter sw = new StringWriter(); 
       newException.printStackTrace(new PrintWriter(sw)); 
       stackTrace.setText(sw.toString()); 
      } 
     }); 
    } 
} 

その後"dynamic root"を使用してFXMLを定義します。

<!-- imports etc --> 

<fx:root type="BorderPane" ...> 

    <center> 
     <TextArea fx:id="stackTrace" editable="false" wrapText="false" /> 
    </center> 
    <top> 
     <Label fx:id="message" /> 
    </top> 
</fx:root> 

今、あなたは、JavaまたはFXML中のいずれかで直接これを使用することができます:

try { 
    // some code... 
} catch (Exception exc) { 
    ExceptionPane excPane = new ExceptionPane(); 
    excPane.setException(exc); 
    Stage stage = new Stage(); 
    stage.setScene(new Scene(excPane)); 
    stage.show(); 
} 

または

<fx:define fx:id="exc"><!-- define exception somehow --></fx:define> 

<ExceptionPane exception="${exc}" /> 
+0

非常に役に立ちます。ありがとうございました :)。 – Askiin

+0

これはfxmlの古いバージョンですか?これをファイルに入れると、シーンビルダはfxmlを開くことができませんでした。それはfx:プレフィックスについて文句を言う。 –

+0

@MaxiWuこれは有効なFXMLである。私はScene Builderの初期のバージョンが ''で問題を抱えていたことを知っています。私はScene Builderでこれをしばらく試していません。あなたはどのバージョンを持っていますか? –

関連する問題