2015-09-14 5 views
0

Для программы, над которой я работаю, я решил создать свою собственную «командную строку», что означает, что сообщения об ошибках, которые обычно отправляются на консоль, отправляются на нее для отладки. Раньше, когда единственной функцией был отображаемый текст, все работало нормально. Теперь, однако, после того, как я сделал корень VBox вместо ScrollPane, форматирование и компоновка странны. Ниже приведена текущая версия консоли, которая не работает, и предыдущая версия, которая отлично работает.

Старый:VBox Contents Not Filling Window

import java.sql.SQLException; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 

import javafx.application.Application; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.ScrollPane; 
import javafx.scene.layout.HBox; 
import javafx.scene.layout.VBox; 
import javafx.scene.paint.Color; 
import javafx.scene.text.Font; 
import javafx.scene.text.FontPosture; 
import javafx.scene.text.FontWeight; 
import javafx.stage.Screen; 
import javafx.stage.Stage; 

public class DebugConsoleOld extends Application { 

    private Stage stage; 
    private SimpleDateFormat dateFormat; 

    public void start(final Stage stage) { 
     this.stage = stage; 

     ScrollPane scrollPane = new ScrollPane(); 
     VBox box = new VBox(); 
     Scene scene = new Scene(scrollPane, Screen.getPrimary() 
       .getVisualBounds().getWidth() - 10, Screen.getPrimary() 
       .getVisualBounds().getHeight() - 10); 

     scrollPane.setStyle("-fx-background-color: black;"); 
     box.setStyle("-fx-background-color: black;"); 
     box.setAlignment(Pos.BOTTOM_LEFT); 

     scrollPane.setContent(box); 

     scrollPane.setFitToHeight(true); 
     scrollPane.setFitToWidth(true); 

     stage.setScene(scene); 
     stage.setTitle("Debug Console"); 
     stage.show(); 

     dateFormat = new SimpleDateFormat("[yyyy-M-d HH:mm:ss] "); 

     write(new Exception(), Priority.MEDIUM); 
     write(new NullPointerException(), Priority.MEDIUM); 
     write(new SQLException(), Priority.MEDIUM); 
    } 

    public void write(String message) { 
     message = dateFormat.format(Calendar.getInstance().getTime()) + message; 
     ((VBox) ((ScrollPane) stage.getScene().getRoot()).getContent()) 
      .getChildren().add(textBuilder(message)); 
    } 

    public void write(String message, Priority priority) { 
     write(message, priority.color); 
    } 

    private void write(String message, Color fontColor) { 
     message = dateFormat.format(Calendar.getInstance().getTime()) + message; 
     ((VBox) ((ScrollPane) stage.getScene().getRoot()).getContent()) 
      .getChildren().add(
        textBuilder(message, null, null, 0, fontColor)); 
    } 

    public void write(Exception exception, Priority priority) { 
     // exception.printStackTrace(); 
     write("--- Beginning of Exception ---", Priority.HIGH); 
     write(exception.toString(), priority); 
     StackTraceElement[] arrayOfStackTraceElement = exception 
       .getStackTrace(); 
     Object localObject2; 
     for (StackTraceElement ste : arrayOfStackTraceElement) 
      write("\t at " + ste, priority); 
     localObject2 = exception.getCause(); 
     if (localObject2 != null) 
      write("Caused by: " + localObject2); 
     write("--- End of Exception ---", Priority.HIGH); 
    } 

    private HBox textBuilder(String text) { 
     return textBuilder(text, null, null, 0, null); 
    } 

    @SuppressWarnings("deprecation") 
    private HBox textBuilder(String text, FontWeight fontWeight, 
      FontPosture fontPosture, double fontSize, Color fontColor) { 
     return javafx.scene.layout.HBoxBuilder 
       .create() 
       .children(javafx.scene.control.CheckBoxBuilder.create().build(), 
        javafx.scene.text.TextBuilder 
          .create() 
          .text(text) 
          .font(Font 
            .font("Consolas", 
              (fontWeight == null ? FontWeight.NORMAL 
                : fontWeight), 
               (fontPosture == null ? FontPosture.REGULAR 
                 : fontPosture), 
               (fontSize <= 0 ? 13 : fontSize))) 
           .wrappingWidth(
             ((ScrollPane) stage.getScene() 
               .getRoot()).getWidth() - 2) 
           .fill((fontColor == null ? Color.WHITE 
             : fontColor)).build()).build(); 
    } 

    public int clear() { 
     int items = ((VBox) ((ScrollPane) ((VBox) stage.getScene().getRoot()) 
       .getChildren().get(0)).getContent()).getChildren().size(); 
     ((VBox) ((ScrollPane) ((VBox) stage.getScene().getRoot()).getChildren() 
       .get(0)).getContent()).getChildren().clear(); 
     return items; 
    } 

    public static enum Priority { 
     /** 
     * A message of no great importance 
      */ 
     LOW(Color.LIGHTGRAY), 
     /** 
     * A message of standard importance, or something not necessary to be 
     * noticed 
     */ 
     NORMAL(Color.WHITE), 
     /** 
     * A message of standard importance, but may need developer attention 
     */ 
     MILD(Color.YELLOW), 
     /** 
     * A message needing attention, as something may have broken 
     */ 
     MEDIUM(Color.ORANGE), 
     /** 
     * A message of great importance, something broke, an exception was 
     * thrown, ect. 
     */ 
     HIGH(Color.RED); 

     private Color color; 

     private Priority(Color color) { 
      this.color = color; 
     } 

    } 

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

} 

ток:

import java.text.SimpleDateFormat; 
import java.util.Calendar; 

import javafx.application.Application; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.ScrollPane; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.Background; 
import javafx.scene.layout.BackgroundFill; 
import javafx.scene.layout.HBox; 
import javafx.scene.layout.VBox; 
import javafx.scene.paint.Color; 
import javafx.scene.text.Font; 
import javafx.scene.text.FontPosture; 
import javafx.scene.text.FontWeight; 
import javafx.stage.Stage; 

public class DebugConsoleNew extends Application { 

    private Stage stage; 
    private SimpleDateFormat dateFormat; 

    public void start(final Stage stage) { 
     this.stage = stage; 

     ScrollPane scrollPane = new ScrollPane(); 
     VBox pane = new VBox(); 
     VBox box = new VBox(); 
     Scene scene = new Scene(pane, 500, 300); 
     final TextField commandField = new TextField(); 

     scrollPane.setStyle("-fx-background-color: black;"); 
     box.setStyle("-fx-background-color: black;"); 
     box.setAlignment(Pos.BOTTOM_LEFT); 

     scrollPane.setContent(box); 
     commandField.setBackground(new Background(new BackgroundFill(
       Color.BLACK, null, null))); 
     commandField.setStyle("-fx-text-fill: white;"); 

     pane.getChildren().addAll(scrollPane, commandField); 

     scrollPane.setFitToHeight(true); 
     scrollPane.setFitToWidth(true); 

     stage.setScene(scene); 
     stage.setTitle("Debug Console"); 
     stage.show(); 

     dateFormat = new SimpleDateFormat("[yyyy-M-d HH:mm:ss] "); 
     commandField.requestFocus(); 
    } 

    public void write(String message) { 
     message = dateFormat.format(Calendar.getInstance().getTime()) + message; 
     ((VBox) ((ScrollPane) ((VBox) stage.getScene().getRoot()).getChildren() 
      .get(0)).getContent()).getChildren().add(textBuilder(message)); 
    } 

    public void write(String message, Priority priority) { 
     write(message, priority.color); 
    } 

    private void write(String message, Color fontColor) { 
     message = dateFormat.format(Calendar.getInstance().getTime()) + message; 
     ((VBox) ((ScrollPane) ((VBox) stage.getScene().getRoot()).getChildren() 
      .get(0)).getContent()).getChildren().add(
      textBuilder(message, null, null, 0, fontColor)); 
    } 

    public void write(Exception exception, Priority priority) { 
     // exception.printStackTrace(); 
     write("--- Beginning of Exception ---", Priority.HIGH); 
     write(exception.toString(), priority); 
     StackTraceElement[] arrayOfStackTraceElement = exception 
       .getStackTrace(); 
     Object localObject2; 
     for (StackTraceElement ste : arrayOfStackTraceElement) 
      write("\t at " + ste, priority); 
     localObject2 = exception.getCause(); 
     if (localObject2 != null) 
      write("Caused by: " + localObject2); 
     write("--- End of Exception ---", Priority.HIGH); 
    } 

    private HBox textBuilder(String text) { 
     return textBuilder(text, null, null, 0, null); 
    } 

    @SuppressWarnings("deprecation") 
    private HBox textBuilder(String text, FontWeight fontWeight, 
      FontPosture fontPosture, double fontSize, Color fontColor) { 
     return javafx.scene.layout.HBoxBuilder 
       .create() 
       .children(
         javafx.scene.control.CheckBoxBuilder.create().build(), 
         javafx.scene.text.TextBuilder 
           .create() 
           .text(text) 
           .font(Font 
             .font("Consolas", 
               (fontWeight == null ? FontWeight.NORMAL 
                 : fontWeight), 
               (fontPosture == null ? FontPosture.REGULAR 
                 : fontPosture), 
               (fontSize <= 0 ? 13 : fontSize)))  
           .wrappingWidth(
             ((VBox) stage.getScene().getRoot()) 
               .getWidth() - 2) 
           .fill((fontColor == null ? Color.WHITE 
             : fontColor)).build()).build(); 
    } 

    public int clear() { 
     int items = ((VBox) ((ScrollPane) ((VBox) stage.getScene().getRoot()) 
       .getChildren().get(0)).getContent()).getChildren().size(); 
    ((VBox) ((ScrollPane) ((VBox) stage.getScene().getRoot()).getChildren() 
       .get(0)).getContent()).getChildren().clear(); 
     return items; 
    } 

    public static enum Priority { 
     /** 
     * A message of no great importance 
     */ 
     LOW(Color.LIGHTGRAY), 
     /** 
     * A message of standard importance, or something not necessary to be 
     * noticed 
     */ 
     NORMAL(Color.WHITE), 
     /** 
     * A message of standard importance, but may need developer attention 
     */ 
     MILD(Color.YELLOW), 
     /** 
     * A message needing attention, as something may have broken 
     */ 
     MEDIUM(Color.ORANGE), 
     /** 
     * A message of great importance, something broke, an exception was 
     * thrown, ect. 
     */ 
     HIGH(Color.RED); 

     private Color color; 

     private Priority(Color color) { 
      this.color = color; 
     } 

    } 

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

} 


Приведенный выше код может быть скопирован в IDE и выполняется. Кто-нибудь есть какие-либо идеи относительно того, почему форматирование становится все вялым?

+1

Объявление о [mcve] не ссылки на код на другом сайте – Reimeus

+0

@Reimeus Обновлен главный вопрос с более компактную версию кода. Однако все, что перечислено выше, необходимо для успешной компиляции/запуска. – ZonalYewHD

+1

Несвязанные, но строители устарели, вам, вероятно, следует реорганизовать ваш код, чтобы не использовать их. Кроме того, вы можете использовать FXML и вставлять ссылки на свои элементы управления в контроллер FXML, а не использовать действительно глубокие инструкции getChildren с приведениями. – jewelsea

ответ

1

Это очень трудно понять, что ваш код пытается сделать, из-за все странные слепки и т.д. Не призывающих как setFitToWidth(true) и setFitToHeight(true) на ScrollPaneScrollPane делают излишний?

Если цель состоит в том, чтобы позволить ScrollPane использовать любое дополнительное пространство, доступное для VBox, вы можете позвонить

VBox.setVgrow(scrollPane, javafx.scene.layout.Priority.ALWAYS); 
+0

Чтобы повторить то, что @jewelsea упомянуто в комментариях выше, вам нужно избавиться от классов-конструкторов, которые [устарели] (http://mail.openjdk.java.net/pipermail/openjfx-dev/2013-March/ 006725.html) и будет полностью удалена в будущей версии (возможно, как только Java 9). –