The idea is: on a TableView of N columns to have the first M columns always visible even when you use the horizontal scroller.
The only thing near my requirement is this Binding two tableviews together such that they scroll in sync.
The idea to put side by side two tables is not the best by my point of view because
1) The sort of the column is partially indipendent between the two tables: if you use the same observableList the rows are sorted in both tables but it is not possible the sort on multiple columns where at least one column is not on the same table
2) There is no syncronous scroll with the mouse wheel or with the arrows keys
I know that, probably, I can cope with problems like these using EventHandlers and Listeners but I am hoping it is possible to use only one table.
So, the question is: are there any configurable properties on TableView or TableColumns to have the behaviour I am looking for?
I am able to freeze columns in javafx table view. We need to create our custom table column class where in we will have two methods setFixed and isFixed which will be used to make some column as fixed.
Apart from this you need to create your own
TableViewskin
TableHeaderRow - basically in this class you need to override the getRootHeader() method
NestedTableColumnHeader - In this class override layoutChildren() method and add new method to layout the fixedColumns
VirtualFlow
TableView - override createDefaultSkin() , add new booleanProperty showColumnHeaderand one ObservableArrayList for fixedTableColumn
TableRow - Override createDefaultSkin()
TableRowSkinBase - override layoutChildren() method to handle fixed columns.
There is currently no such feature. In fact, even manipulating the scroll bar and responding to scrollbar events are problematic. Two options I can think of:
Option #1 - Multiple Table
Create a new layout which contains the two tables and two scroll bars like in the FXML snippet below:
<BorderPane prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<bottom>
<ScrollBar fx:id="hScroll" />
</bottom>
<center>
<HBox fx:id="varTable" prefHeight="100.0" prefWidth="200.0">
<children>
<TableView fx:id="fixedTable" prefHeight="200.0" prefWidth="200.0">
<columns>
<TableColumn prefWidth="75.0" text="Column X" />
<TableColumn prefWidth="75.0" text="Column X" />
</columns>
</TableView>
<TableView prefHeight="200.0" prefWidth="200.0" HBox.hgrow="ALWAYS">
<columns>
<TableColumn prefWidth="75.0" text="Column X" />
<TableColumn prefWidth="75.0" text="Column X" />
</columns>
</TableView>
</children>
</HBox>
</center>
<right>
<ScrollBar fx:id="vScroll" orientation="VERTICAL" />
</right>
</BorderPane>
Note the second tabe has HBox.hgrow="ALWAYS" set.
Write a function to locate the scroll bar in a TableView:
private static final ScrollBar getScrollBar(final TableView<?> tableView) {
for (final VirtualFlow virtualFlow: Nodes.filter(Nodes.descendents(tableView, 2), VirtualFlow.class)) {
for (final Node subNode: virtualFlow.getChildrenUnmodifiable()) {
if (subNode instanceof ScrollBar && ((ScrollBar)subNode).getOrientation() == Orientation.VERTICAL) {
return (ScrollBar)subNode;
}
}
}
return null;
}
Use this to locate the two vertical scroll bars and bind their properties (like min, max, value etc.) to your own vertical scroll bar and then hide the original scroll bars. You will also need to set managed=false so that they do not take up space in the layout.
Locate and hide the horizontal scroll bars and bind the properties of the 'moving' table horizontal scroll bar to your own horizontal scroll bar.
We are succesfully using this technique to link two tables with a single scroll bar while waiting for this Jira to be fixed.
Option #2 - Write your own TableViewSkin
Download the JavaFx source to see what they do with the skin and then you can either write a complete custom skin or write a skin that wraps two regular skins and implement in a similar way to Option #1 above
So, the question is: are there any configurable properties on TableView or TableColumns to have the behaviour I am looking for?
Apparently not, but there is a feature request for this behavior on the JavaFX Jira (you'll need to register to view it):
https://javafx-jira.kenai.com/browse/RT-19454
I suggest you vote for it. :^)
JavaFX doesn't have this functionality. Check out ControlsFX's SpreadsheetView.
Code worked with javafx 11
import javafx.application.Platform;
import javafx.scene.AccessibleAttribute;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.TableCell;
import javafx.scene.layout.Region;
public class LockedTableCell<T, S> extends TableCell<T, S> {
{
Platform.runLater(() -> {
try {
ScrollBar scrollBar = (ScrollBar) getTableView()
.queryAccessibleAttribute(AccessibleAttribute.HORIZONTAL_SCROLLBAR);
// set fx:id of TableColumn and get region of column header by #id
Region headerNode = (Region) getTableView().lookup("#" + getTableColumn().getId());
scrollBar.valueProperty().addListener((ob, o, n) -> {
double doubleValue = n.doubleValue();
// move header and cell with translateX & bring it front
headerNode.setTranslateX(doubleValue);
headerNode.toFront();
this.setTranslateX(doubleValue);
this.toFront();
});
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
Using it (with first M columns)
tableColumnInstance1.setCellFactory(param -> new LockedTableCell<>() {...});
tableColumnInstance2.setCellFactory(param -> new LockedTableCell<>() {...});
...
tableColumnInstanceM.setCellFactory(param -> new LockedTableCell<>() {...});
Related
I have a container that needs to display two custom components scaled down by 25% aligning them vertically.
I'm using a VBox loaded from this FXML:
<fx:root type="VBox" fx:id="leaderDisplay" xmlns="https://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="MyController"
prefHeight="720.0" prefWidth="200.0" alignment="CENTER">
</fx:root>
And the component is loaded from this FXML:
<fx:root stylesheets="#css/style.css" type="StackPane"
maxHeight="294.0" maxWidth="195.0"
fx:controller="MyOtherController"
xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1">
<AnchorPane fx:id="cardPane" styleClass="leader-card" prefHeight="294.0" prefWidth="195.0">
<FlowPane fx:id="lcRequirements" layoutX="13.0" layoutY="10.0" />
<Label fx:id="lcVictoryPoints" layoutX="87.0" layoutY="162.0" prefHeight="25.0" prefWidth="20.0" text="0" />
</AnchorPane>
<Pane fx:id="cardBack" styleClass="leader-card-back" maxHeight="294.0" maxWidth="195.0" visible="false" />
</fx:root>
I add the needed components programmatically with this method in the VBox controller:
private void addLeader(LeaderCard newLeader) {
Platform.runLater(() -> {
setStyle("-fx-background-color: grey;");
LeaderCardWidget newWidget = new LeaderCardWidget(newLeader);
System.out.println("Height before: " + newWidget.getMaxHeight());
newWidget.setStyle("-fx-border-color: black;" +
"-fx-border-width: 3");
newWidget.setScaleX(0.75);
newWidget.setScaleY(0.75);
System.out.println("Height after: " + newWidget.getMaxHeight());
leaderDisplay.getChildren().add(newWidget);
leadersAndWidgets.put(newLeader, newWidget);
});
}
The problem is that the components are being scaled down, but the vbox does not display them properly, leaving huge spacing around them (to the right is the same screenshot without scaling for reference):
From the "Visual Bounds versus Layout Bounds" section of the layout documentation:
Node provides the layoutBounds property to define the 'logical'
bounds of the node for layout and boundsInParent to define the visual
bounds once all effects, clipping, and transforms have been applied.
... if a ScaleTransition is used to pulse the size of a button,
that pulse animation will not disturb layout around that button. If an
application wishes to have the effect, clip, or transform factored
into the layout of a node, it should wrap that node in a Group.
In short, transforms, such as scaling, are not factored into the layout calculations of the parent. You can make that happen by wrapping your components in a group. I think you can achieve this in your code with
// leaderDisplay.getChildren().add(newWidget);
leaderDisplay.getChildren().add(new Group(newWidget));
Relevant FXML :
<ScrollPane fx:id="scrollpane_var" hbarPolicy="NEVER" prefHeight="200.0" prefWidth="200.0" GridPane.columnSpan="3" GridPane.rowIndex="2" GridPane.rowSpan="5">
<content>
<TableView fx:id="tableview_var" prefHeight="169.0" prefWidth="292.0">
<columns>
<TableColumn prefWidth="69.0" text="Quantité" />
<TableColumn prefWidth="161.0" text="Nom" />
<TableColumn prefWidth="56.0" text="Prix" />
</columns>
</TableView>
</content>
</ScrollPane>
Controller class Code :
public class Lancer {
#FXML // fx:id="scrollpane_var
private ScrollPane scrollpane_var; // Value injected by FXMLLoader
#FXML // fx:id="tableview_var"
private TableView<String> tableview_var; // Value injected by FXMLLoaderte void initialize()
public void initialize() {
tableview_var.prefWidthProperty().bind(scrollpane_var.prefWidthProperty());
}
Visual Representation :
Click to see Scenebuilder screenshot
as the title says i'm trying to bind a TableView's width to it's Parent container and the documentation is a bit confusing as i am very new to GUI Applications .
This line of code is the furthest i've gottent and i dont know why it's not working :
public void initialize() {
tableview_var.prefWidthProperty().bind(scrollpane_var.prefWidthProperty());
}
A TableView manages its own scrolling, so you should not be putting it inside a ScrollPane at all. Just omit the scroll pane from the layout entirely.
In general, if you want the content of a scroll pane to fit the available width of the scroll pane, you would use the fitToWidth property, instead of trying to use a binding. In general, binding the pref width like this is a bad idea; if the layout or container you are using doesn't provide the functionality you need, and it almost always will, you should subclass Pane and override layoutChildren() and other methods. Here, the TableView already provides scrolling, and in more general cases, the ScrollPane allows you to specify the content should fit the width of the scroll pane.
<ScrollPane ... fitToWidth="true>
<!-- ... -->
</ScrollPane>
But again, here the scroll pane is redundant.
I am looking for a way to say set a maxWidth size to 80% in FXML.
Much like in web development.
<VBox fx:id="testVB" prefWidth="600">
But this does not:
<VBox fx:id="testVB" prefWidth="80%">
I know that in Straight JavaFX2 non-fxml you can create insets? What is the best way to do this outside of code in FMXL?
Thanks!
Riley
I'm not sure you can. You need to use the GridPane layout component. In this component, you can specify rows and columns constraints, and in these constraints you can specify a width as a percentage. For example:
<GridPane>
<children>
<TitledPane text="testGridPane" GridPane.columnIndex="0" GridPane.rowIndex="0" />
</children>
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" percentWidth="80.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" percentWidth="20.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
</GridPane>
This code defines a GridPane with a first column with a width of 80%. The TitledPane is set in the first cell of the first column of this GridPane, and can (because you need to be sure that the width constraints of the TitledPane match your needs) occupy 80% of the width of the GridPane.
Please note that I removed all information not relevant to your question. By the way, Oracle's Scene Builder tool is very useful to define complex FXML layout.
It seems like many answers have already been provided and they should work. However, there is a way to set percentages:
<fx:define>
<Screen fx:factory="getPrimary" fx:id="screen" />
</fx:define>
This would help you detect the dimensions of the current screen, the application is being displayed on. Now that we have the display dimensions, we can play with it in FXML as follows:
<HBox fx:id="hroot" prefHeight="${screen.visualBounds.height}" prefWidth="${screen.visualBounds.width}"> Your FXML elements inside the root... </HBox>
Note that I use visualBounds, since this would get me the available space on the screen, since I don't want an overlap with the taskbar in Windows for example. For fullscreen applications, you would just use 'bounds'.
Now, to come to your point of using percentages, you can actually play with the value of the prefheight and prefWidth. You can put calculations inside the ${}.
Optionally:
If you want to have all your elements use relative sizes, just refer to them, using their ID and width or height property, and make your calculation.
<VBox fx:id="VBSidebar" prefWidth="${hroot.width*0.15}" prefHeight="${hroot.height}"> more elements.. </VBox>
Hope this helps!
You can simulate it - basic example that simulates 50% for two cols in an HBox. You can add dummy panes to get thirds, etc.
HBox {
VBox {
static hgrow : "ALWAYS",
Label {
text : "Privacy",
alignment : "CENTER",
styleClass : ["h2", "heading"]
}
},
VBox {
static hgrow : "ALWAYS",
Label {
text : "Messages",
alignment : "CENTER",
styleClass : ["h2", "heading"]
},
Label {text:""}
}
}
I've got a Java project I'm working on that uses JavaFX to generate a UI. I'm not much of a Java programmer (not much of a programmer in general - I'm a CS student), so it's a bit of a learning experience, but generally I'm answering my own questions as I go. I'm now hitting a sticky spot with a TableView, though, and getting a bit lost - specifically, I can't seem to set any kind of action in response to interacting with the TableView.
The current layout of my project is Main.java, Controller.java and UI.fxml. In Main the pane/scene is loaded from UI.fxml as the program starts. (Technically the project contains several other bits of code, but I'm trying to only post what's relevant.) I have a TableView defined in UI.fxml as so:
<TableView fx:id="queueTable">
<columns>
<TableColumn text="Title">
<cellValueFactory>
<PropertyValueFactory property="tableTitle"/>
</cellValueFactory>
</TableColumn>
<TableColumn text="Artist">
<cellValueFactory>
<PropertyValueFactory property="tableArtist"/>
</cellValueFactory>
</TableColumn>
<TableColumn text="Album">
<cellValueFactory>
<PropertyValueFactory property="tableAlbum"/>
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
Similarly I have several buttons defined in UI.fxml with onAction as so:
<Button fx:id="buttonQueueAdd" text="Add" onAction="#addMediaToQueue"/>
In my previous code I was able to define an event for when an item in the TableView was selected, in the method where my TableView was being generated. Now, however, all the UI creation is done via the FXML file. The FXML file has a controller class it refers to (Controller.java), where all the actions are defined for the various buttons, but I can't seem to get it to accept any attribute like onAction, setOnMousePressed, etc. in the FXML file for the TableView like it accepts an 'onAction' attribute for the Button.
It seems like I can get a workaround going by defining the action in my Main class (or creating a method in my Controller class that's called in the Main class, when the scene is being created), but that won't work unless I make queueTable static in my Controller class... which then breaks all the functions that manipulate items in the TableView - for example, I can no longer add items to the TableView/the UI does not refresh to show items are added.
It seems like the best solution is to not have the TableView created in FXML, to instead have the TableView created and all its onMousePressed events and etc. set up outside of the FXML file and have them added to the scene in my Main class's start method. This is how it was done previously, and it worked acceptably then. However, that seems messy, and leads to my UI elements being strewn across multiple classes and/or the FXML file - this is a project I'm working on with several other students, and I'm trying to keep everything as streamlined/organized as possible. Do I have to bite the bullet and do it the "messy" way, or is there a better option?
You can still generate the TableView using the fxml, but add a initialize method to the controller. This method is invoked by the FXMLLoader after it's done creating the object stucture and can be used to do modifications to the object structure that you cannot do from fxml:
#FXML
private void initialize() {
queueTable.getSelectionModel().selectedIndexProperty().addListener((observable, oldValue, newValue) -> {
...
});
}
In case you need to add this listener from Main, you could add a method to the controller and get the controller from the FXMLLoader instance you use to create the fxml.
Controller
public void addSelectedIndexListener(ChangeListener<? super Number> listener) {
queueTable.getSelectionModel().selectedIndexProperty().addListener(listener);
}
Main
FXMLLoader loader = new FXMLLoader(fxmlUrl);
myNode = loader.load();
Controller controller = loader.getController();
controller.addSelectedIndexListener((observable, oldValue, newValue) -> {
...
});
Note that is an property property should depend on a property of the selection model, you may be able to use expression binding to achieve the desired effect.
<BorderPane xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1">
<center>
<TableView fx:id="table" BorderPane.alignment="CENTER">
<columns>
<TableColumn text="value">
<cellValueFactory>
<PropertyValueFactory property="value"/>
</cellValueFactory>
</TableColumn>
</columns>
<items>
<FXCollections fx:factory="observableArrayList">
<Item value="Hello World"/>
<Item value="42"/>
</FXCollections>
</items>
</TableView>
</center>
<left>
<Button mnemonicParsing="false" text="Remove" BorderPane.alignment="CENTER" disable="${table.selectionModel.selectedIndex+0<0}" />
</left>
</BorderPane>
Note that the table.selectionModel.selectedIndex+0<0 part is a workaround used, since JavaFX currently doesn't use null-safe equality checks (table.selectionModel.selectedItem==null doesn't work) and cannot get the type of the 0 constant right for comparison (table.selectionModel.selectedIndex<0), so this currently doesn't seem like a good option.
I have a plain CheckBox in an FXML file on the same line as some other controls and labels in a HBox.
The checkBox label text-base is about 6px units lower than ALL the other text and labels on the same line (HBox).
I can manually line things up in SceneBuilder by specifying a padding-bottom value of: 6. I wanted to put that into the CSS so all checkbox labels would be "lined-up", but everthing I've tried is ignored and doesn't show in the CSS Analyzer (too).
I looked through the Checbox default styling as pointed out here:
Styling a checkbox and also:
Checkbox in the UI controls
I had similar issues with ListBox where the control is constructed from a number of components. You have to know which 'thing' is relevant. However, looking through: com/sun/javafx/scene/control/skin/
caspian/caspian.css
I can't pick the component that makes the text label lower than other text on the same line/row. Add to that, the fact that specifying the padding in the SceneBuilder designer layout, will fix the issue on a one-by-one (manual) basis, it just seems strange that it won't work for:
.check-box {
padding-bottom: 6px; /* or just 6 */
}
Does not work on the following FXML mark-up.
<HBox alignment="CENTER_LEFT" >
<children>
<CheckBox fx:id="acknowledged" alignment="TOP_LEFT" styleClass="normal" text="00">
<padding>
<Insets bottom="6.0" left="4.0" right="8.0" />
</padding>
</CheckBox>
<Button fx:id="detailButton" text="%alarm.detail.label" />
<Label fx:id="alarmType" styleClass="normal" text="%alarm.type.value">
<padding>
<Insets left="8.0" right="8.0" />
</padding>
</Label>
</children>
</HBox>
The objective is to define the padding-bottom via CSS rather than have to do it manually in the FXML:
<padding>
<Insets bottom="6.0" left="4.0" right="8.0" />
</padding>
Any ideas?
To be clear, the visual result for this row is that the checkbox itself has a base-line smaller/lower than the other elements (button, label). The CheckBox label is also subsequently "below" the other elements. If we can pad using CSS, then we don't need to manually maintain the layouts.
As a general rule, alignment problems should be solved by the layout (vs. tweaking paddings or such). So first stop to a solution could be the doc of the parent pane, here HBox:
The alignment of the content is controlled by the alignment property,
which defaults to Pos.TOP_LEFT.
That might be consistent with what you are be seeing (can't be 100% certain, though, as you forgot to include a runnable example ;-) If all other components on the line are accidentally being same height or filling the box with the checkbox smaller, it will positioned at the top of the pane.
Assumed solution is to change the pane's alignment to BASELINE_XX, quick check in code works fine for me:
private Parent getContent() {
HBox box = new HBox(new TextField("something"),
new CheckBox("soso"), new Button("hello"));
box.setAlignment(Pos.BASELINE_CENTER);
return box;
}