2012-12-04 22 views
18

sto creando un'applicazione in JavaFX, in cui voglio fare che se ogni fase del bambino è sempre aperta, allora dovrebbe essere aperto nel centro del palco genitore. Sto provando a farlo usando mystage.centerOnScreen() ma assegnerò la fase secondaria al centro dello schermo, non il centro dello stadio genitore. Come posso assegnare lo stadio secondario al centro dello stadio genitore?Centro posizione del palco

private void show(Stage parentStage) { 
    mystage.initOwner(parentStage); 
    mystage.initModality(Modality.WINDOW_MODAL); 
    mystage.centerOnScreen(); 
    mystage.initStyle(StageStyle.UTILITY); 
    mystage.show(); 
} 

risposta

22

È possibile utilizzare le proprietà X/Y/larghezza/altezza dello stage parent per farlo. Piuttosto che usare Stage#centerOnScreen, si potrebbe procedere come segue:

public class CenterStage extends Application { 
    @Override 
    public void start(final Stage stage) throws Exception { 
     stage.setX(300); 
     stage.setWidth(800); 
     stage.setHeight(400); 
     stage.show(); 

     final Stage childStage = new Stage(); 
     childStage.setWidth(200); 
     childStage.setHeight(200); 
     childStage.setX(stage.getX() + stage.getWidth()/2 - childStage.getWidth()/2); 
     childStage.setY(stage.getY() + stage.getHeight()/2 - childStage.getHeight()/2); 
     childStage.show(); 
    } 

    public static void main(String[] args) { 
     Application.launch(args); 
    } 
} 
+1

Se non si imposta in modo esplicito la larghezza e l'altezza del childStage, allora si può eseguire il calcolo in un gestore di eventi per l'evento childStage.setOnShown. – axiopisty

+0

Per quanto possa sembrare pauroso, quando faccio questo il palcoscenico prende le sue dimensioni ... \t \t \t \t childStage.toBack(); \t \t childStage.show(); \t \t childStage.hide(); \t \t childStage.toFront(); –

1

Quando non si determina una dimensione per la childStage, bisogna ascoltare per la larghezza e l'altezza cambia la larghezza e l'altezza è ancora NaN quando viene chiamato onShown .

final double midX = (parentStage.getX() + parentStage.getWidth())/2; 
final double midY = (parentStage.getY() + parentStage.getHeight())/2; 

xResized = false; 
yResized = false; 

newStage.widthProperty().addListener((observable, oldValue, newValue) -> { 
    if (!xResized && newValue.intValue() > 1) { 
     newStage.setX(midX - newValue.intValue()/2); 
     xResized = true; 
    } 
}); 

newStage.heightProperty().addListener((observable, oldValue, newValue) -> { 
    if (!yResized && newValue.intValue() > 1) { 
     newStage.setY(midY - newValue.intValue()/2); 
     yResized = true; 
    } 
}); 

newStage.show(); 
Problemi correlati