Home > Enterprise >  How to set vBarPolicy in ScrollPane ? JavaFX
How to set vBarPolicy in ScrollPane ? JavaFX

Time:03-10

I'm trying to set vertical scroll bar to be always visible. But i want to do it, using only fxml. Currently I;m trying to do this, like this:

  <ScrollPane fitToHeight = "true" fitToWidth = "true">
     <vbarPolicy>
        <ScrollBarPolicy fx:constant = "ALWAYS" />
     </vbarPolicy>
     <LogView fx:id = "logViewLog" />
  </ScrollPane>

But I got this error:

Caused by: javafx.fxml.LoadException: ScrollBarPolicy is not a valid type.

CodePudding user response:

Recommended Solution

Set the vbarPolicy property directly to a string value of the ScrollBarPolicy enumerated type: vbarPolicy="ALWAYS".

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.control.Label?>

<ScrollPane fitToHeight = "true" fitToWidth = "true" vbarPolicy="ALWAYS">
    <Label text="The quick brown fox jumped over the lazy dog" minHeight="100" wrapText="true" alignment="TOP_LEFT"/>
</ScrollPane>

This will work for any enumerated type property.

See for instance in the example how alignment="TOP_LEFT", similarly sets the value of the Pos enumerated type alignment property for the Label.

Alternate Solution

As Slaw noted in comments you can also do this in a long-hand fashion using the fx:constant syntax:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ScrollPane.ScrollBarPolicy?>

<ScrollPane fitToHeight = "true" fitToWidth = "true" xmlns:fx="http://javafx.com/fxml">
    <vbarPolicy>
        <ScrollPane.ScrollBarPolicy fx:constant = "ALWAYS" />
    </vbarPolicy>
    <Label text="The quick brown fox jumped over the lazy dog" minHeight="100" wrapText="true" alignment="TOP_LEFT"/>
</ScrollPane>

If you do this, ensure that you:

  1. Define the fx namespace:

    xmlns:fx="http://javafx.com/fxml"
    
  2. Import the ScrollBarPolicy type:

    <?import javafx.scene.control.ScrollPane.ScrollBarPolicy?>
    

My preference would be to use the direct string conversion previously outlined rather than the fx:constant version.

  • Related