First, code that generates a UI that illustrates the problem:
package test;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(final String[] args) throws Exception {
launch(args);
}
#Override
public void start(final Stage window) throws Exception {
// Create a VBox to hold the table and button
final GridPane root = new GridPane();
root.setHgap(5);
root.setVgap(5);
// Add a combo-box to the first row
final ComboBox<String> dropdown1 = new ComboBox<>();
dropdown1.getItems().add("Option 1");
dropdown1.getSelectionModel().selectFirst();
root.add(dropdown1, 0, 0);
// Add a checkbox to the first row
final CheckBox checkbox1 = new CheckBox("CB Text 1");
root.add(checkbox1, 1, 0);
// Add a combo-box to the second row
final ComboBox<String> dropdown2 = new ComboBox<>();
dropdown2.getItems().add("Option 2");
dropdown2.getSelectionModel().selectFirst();
root.add(dropdown2, 0, 1);
// Add a checkbox, wrapped in an HBox, to the second row
final CheckBox checkbox2 = new CheckBox("CB Text 2");
final HBox hbox = new HBox(checkbox2);
hbox.setAlignment(Pos.BASELINE_LEFT);
root.add(hbox, 1, 1);
GridPane.setValignment(hbox, VPos.BASELINE);
// Show the JavaFX window
final Scene scene = new Scene(root);
window.setScene(scene);
window.show();
}
}
The above code generates the following UI (Java 8u102 Windows x64):
As shown in the image, the vertical alignment of the CheckBox in the second row is misaligned with the ComboBox. I expect everything to be aligned on the text baseline. How can I get the second row in the GridPane to match the alignment of the first row, without removing the HBox?
Modify the code that populates the offending cell to be the following:
// Add a checkbox, wrapped in an HBox, to the second row
final CheckBox checkbox2 = new CheckBox("CB Text 2");
final HBox hbox = new HBox(checkbox2);
hbox.setFillHeight(true); // Added this
hbox.setAlignment(Pos.CENTER_LEFT);// Changed the alignment to center-left
root.add(hbox, 1, 1);
//GridPane.setValignment(hbox, VPos.BASELINE); This is unnecessary
This code will force the HBox to be the same height as the row, then vertically center the CheckBox within it.
Related
I am making a Login Screen with a number pad, and I can't seem to center align a GridPane of buttons in a Pane. What am I doing wrong?
Main.java
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.input.KeyCombination;
import javafx.stage.Screen;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args){
launch(args);
}
public void start(Stage primaryStage) throws Exception{
Rectangle2D bounds = Screen.getPrimary().getBounds();
LoginScreen loginScreen = new LoginScreen(bounds.getWidth(), bounds.getHeight());
Scene scene = new Scene(loginScreen.get());
primaryStage.setScene(scene);
primaryStage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
primaryStage.show();
primaryStage.setFullScreen(true);
}
}
LoginScreen.java
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
public class LoginScreen {
private Pane root;
private GridPane numberPad;
public LoginScreen(double screenWidth, double screenHeight){
root = new Pane();
root.setPrefSize(screenWidth, screenHeight);
root.setBackground(new Background(new BackgroundFill(Color.AQUA, CornerRadii.EMPTY, Insets.EMPTY)));
numberPad = new GridPane();
Button button01 = new Button("1");
Button button02 = new Button("2");
Button button03 = new Button("3");
Button button04 = new Button("4");
Button button05 = new Button("5");
Button button06 = new Button("6");
Button button07 = new Button("7");
Button button08 = new Button("8");
Button button09 = new Button("9");
numberPad.setAlignment(Pos.CENTER);
numberPad.add(button01, 0, 0);
numberPad.add(button02, 1, 0);
numberPad.add(button03, 2, 0);
numberPad.add(button04, 0, 1);
numberPad.add(button05, 1, 1);
numberPad.add(button06, 2, 1);
numberPad.add(button07, 0, 2);
numberPad.add(button08, 1, 2);
numberPad.add(button09, 2, 2);
root.getChildren().addAll(numberPad);
}
public Pane get(){
return root;
}
}
GUI code is verbose, and this post editor isn't letting me post my question as is, so I need these extra lines to get it to accept my question. If I thought I could cut down my code to just the numberPad.setAlignment(Pos.Center) and still make it clear how I am attempting to center my GridPane I most certainly would. I do humbly thank those who might lend me their time to help me solve this issue I have.
Edit 01:
My issue is that the GridPane itself is drawn in the top left corner of the screen rather than in the center of the screen.
You need to actually set the alignment for the parent container. A Pane is not a valid container for doing this, however.
If you were to use a VBox instead, you could simply set its alignment as so:
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
That will cause all of the children of the VBox to be placed in the center.
The Pos enum also provides other methods of positioning, including TOP_CENTER, TOP_LEFT, and BOTTOM_RIGHT, for example.
So Im trying to have text on the left and buttons on the right, text should have constant size and buttons should resize to fill the rest of the window.
Here is my result so far:
I dont want my text over buttons, I want them to share the whole window.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
GridPane buttons = new GridPane();
GridPane textGrid = new GridPane();
#Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
Button button1 = new Button();
Button button2 = new Button();
Button button3 = new Button();
Button button4 = new Button();
Button button5 = new Button();
button1.setText("Button1");
button2.setText("Button4");
button3.setText("Button3");
button4.setText("Button4");
button5.setText("Button5");
TextArea text1 = new TextArea();
text1.setText("Test");
text1.setPrefSize(100, 100);
button1.prefWidthProperty().bind(buttons.widthProperty());
button2.prefWidthProperty().bind(buttons.widthProperty());
button3.prefWidthProperty().bind(buttons.widthProperty());
button4.prefWidthProperty().bind(buttons.widthProperty());
button5.prefWidthProperty().bind(buttons.widthProperty());
button1.prefHeightProperty().bind(buttons.heightProperty());
button2.prefHeightProperty().bind(buttons.heightProperty());
button3.prefHeightProperty().bind(buttons.heightProperty());
button4.prefHeightProperty().bind(buttons.heightProperty());
button5.prefHeightProperty().bind(buttons.heightProperty());
buttons.addColumn(0, button1, button2, button3, button4, button5);
textGrid.addColumn(0, text1);
Scene scene = new Scene(root, 280, 180);
root.getChildren().addAll(buttons, textGrid);
buttons.setAlignment(Pos.TOP_RIGHT);
textGrid.setAlignment(Pos.TOP_LEFT);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
It is usually better to let the layout panes handle the layout management rather than trying to manage the layout through bindings.
Here is a sample:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.util.stream.IntStream;
public class Main extends Application {
private static final int N_BUTTONS = 5;
#Override
public void start(Stage stage) {
VBox buttonLayout = new VBox(
10,
IntStream.range(0, N_BUTTONS)
.mapToObj(this::createButton)
.toArray(Button[]::new)
);
HBox.setHgrow(buttonLayout, Priority.ALWAYS);
TextArea textArea = new TextArea("Test");
textArea.setPrefWidth(100);
textArea.setMaxWidth(TextArea.USE_PREF_SIZE);
textArea.setMinWidth(TextArea.USE_PREF_SIZE);
HBox layout = new HBox(10, textArea, buttonLayout);
layout.setPadding(new Insets(10));
Scene scene = new Scene(layout);
stage.setScene(scene);
stage.show();
}
private Button createButton(int i) {
Button button = new Button("Button " + i);
// button.setMaxWidth(Double.MAX_VALUE);
button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
VBox.setVgrow(button, Priority.ALWAYS);
return button;
}
public static void main(String[] args) {
launch(args);
}
}
Here are a couple of things I would point out based upon the sample:
As the buttons are so similar, create the buttons in a loop rather than individually in code. I use an IntStream range with a map and a toArray, but you could do the same thing with a standard for loop (which may be easier to understand).
Use combinations of standard layout panes to achieve your layout. For example the buttons are vertically spaced, so put them in a VBox, the text and the buttons are horizontal to each other, so use a HBox.
Use constraints on the layouts to massage them into performing the layout you like, for example, HBox.setHgrow(buttonLayout, Priority.ALWAYS); tells the Box to always assign any extra additional space in the Box to the buttonLayout so that the buttons will fill any remaining area.
Set constraints on the individual nodes to size them how you wish, for example the following code establishes a fixed width for the textArea, which will not vary (you could similar code to establish a fixed height if you wished):
textArea.setPrefWidth(100);
textArea.setMaxWidth(TextArea.USE_PREF_SIZE);
textArea.setMinWidth(TextArea.USE_PREF_SIZE);
Some controls will automatically expand themselves beyond their max size, buttons do not by default, to enable this behavior use the following code (if you only wanted the width to expand and not the height then you would only set the maxWidth rather than the maxSize):
button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
Rather than defining layouts in code as in this example, instead use a tool such as SceneBuilder to create the scene visually and save the layout as an FXML file, so that the layout is separated from your code (similarly place any styling in an external CSS file).
I have a JavaFX BorderPane, inside of which there is a GridPane for holding contents. The GridPane consists of two columns, one for a Text with a Label (both in a VBox) and one for a Button. The text column is supposed to be 80% width and the button column is supposed to be 20% width. When I set the text of the Text and it is wider than the column, it wraps to the width of the VBox. However, when I change the size of the Window to make it wider and then shrink the Window back the text in the Text does not shrink back.
You can see my attempts at limiting the width in the wireListeners function of TestMainView. I have tried different combos of things but have gotten nothing to work.
Here is my code:
Launcher:
package com.test.app;
import com.test.app.view.TestMainView;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class TestGuiApplication extends Application {
#Override
public void start(Stage initialStage) throws Exception {
TestMainView mainView = new TestMainView();
initialStage.setScene(new Scene(mainView.getView(), 300, 300));
mainView.init();
initialStage.show();
}
public static void main(String args[]){
launch(args);
}
}
GUI:
package com.test.app.view;
import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
public class TestMainView {
private BorderPane borderPane;
private GridPane gridPane;
private VBox viewBox;
private VBox selectedItemsColumn;
private Label selectedItemsTitleLabel;
private Text selectedItemsList;
private Button goButton;
public TestMainView() {
this.borderPane = new BorderPane();
}
public void init() {
createView();
wireListeners();
}
public BorderPane createView(){
borderPane.setCenter(createCenterView());
return borderPane;
}
public void wireListeners(){
goButton.setOnMouseClicked((event) -> {
selectedItemsList.setText(selectedItemsList.getText() + "- X X X X X X");
});
//Tried the following listeners to prevent the text from growing otuside column size:
//Keep border pane width matched to Scene
borderPane.prefHeightProperty().bind(borderPane.getScene().heightProperty());
borderPane.prefWidthProperty().bind(borderPane.getScene().widthProperty());
//Set text wrapping width to bind to its VBox, this worked
selectedItemsList.wrappingWidthProperty().bind(selectedItemsColumn.widthProperty());
//Set VBox width to match the gridpane column width
selectedItemsColumn.prefWidthProperty().bind(gridPane.getColumnConstraints().get(0).percentWidthProperty());
}
public VBox createCenterView(){
viewBox = new VBox();
viewBox.getChildren().add(createGridView());
return viewBox;
}
public GridPane createGridView(){
gridPane = new GridPane();
selectedItemsColumn = new VBox();
selectedItemsTitleLabel = new Label("Selected items:");
selectedItemsList = new Text("X X X X X X");
selectedItemsColumn.getChildren().addAll(selectedItemsTitleLabel, selectedItemsList);
gridPane.add(selectedItemsColumn, 0, 0);
goButton = new Button("Go!");
gridPane.add(goButton, 1, 0);
ColumnConstraints col1 = new ColumnConstraints();
col1.setPercentWidth(80);
ColumnConstraints col2 = new ColumnConstraints();
col2.setPercentWidth(20);
gridPane.getColumnConstraints().addAll(col1, col2);
gridPane.setHgap(10);
gridPane.setVgap(10);
gridPane.setPadding(new Insets(10,10,10,10));
gridPane.setGridLinesVisible(true);
return gridPane;
}
public Parent getView(){
return borderPane;
}
}
How can I get the Text contents of my VBox to match their width to that of the GridPane column and not overflow the column?
.button
{
-fx-background-image: url("mapDefault.png");
-fx-pref-width: 10px;
-fx-pref-height: 10px;
}
My button looks like this, and theoretically, it should fit the image (10x10) exactly. However
It returns that the button is about 30px in height, despite that I changed it. The button is declared like
Button beachButton = new Button();
and does not have any text values in it.
Any possible causes to this increase/min-cap in height?
Any changes in text need to be taken into account, especially custom font. To accommodate for any picture sizes smaller than the font of the item, set the font size equal to 0px as well.
The offset of the icon(or text) from the buttons border may be the problem. A Button with text in default font type & size cannot get smaller in height than 25px (using setPrefHeight() or setStyle(...)). To make the height the same as other controls the padding could be reduced as in the following example:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class SmallerButtons extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
Label label1= new Label ("Label1");
Label label2= new Label ("Label2");
CheckBox checkBox1= new CheckBox ("CheckBox1");
CheckBox checkBox2= new CheckBox ("CheckBox2");
Button button1= new Button ("Button1");
Button button2= new Button ("Button2");
Button button3= new Button ("Button3");
button3.setOnAction(a-> System.out.println(label1.getHeight() + " / " +checkBox1.getHeight() + " / " +button1.getHeight()));
label1.setStyle("-fx-font-size:10");
button1.setPadding(new Insets(0,3,0,3)); // <----- this one works. Standard value is 5.0.
button1.setMaxWidth(200);
button2.setPrefHeight(17); // no effect
button3.setStyle("-fx-pref-height:35px"); // or also setPrefHeight(35)
VBox vb1=new VBox(label1,label2);
VBox vb2=new VBox(checkBox1,checkBox2);
VBox vb3=new VBox(button1, button2, button3);
vb3.setMaxWidth(80);
vb1.setSpacing(1);
vb2.setSpacing(1);
vb3.setSpacing(1);
HBox hb = new HBox(vb1,vb2,vb3);
hb.setSpacing(15);
Scene scene = new Scene(hb);
stage.setOnCloseRequest((e)->System.exit(0));
stage.setScene(scene);
stage.show();
}
}
One catch: With one buttons padding adjusted all other buttons need the padding explicitly set, too.
Converting from Swing to FX here. We have some CheckBoxes where the Label appears on the left side of the CheckBox. We are accomplishing this by calling
setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT);
The problem is that in some GridPanes, we'll have a Label in column 0 with a Node in column 1 on row 1, and then one of the CheckBoxes in the second row. Ideally the CheckBox and Node are aligned with each other. I am currently accomplishing this by setting the CheckBox's columnSpan to 2, and adding some right padding to align the fields. Is there an easier way to be doing this?
Our previous solution was to just separate the Label from the CheckBox, however this caused us to lose the functionality of selecting/deselecting the CheckBox upon clicking the label.
EDIT:
I'm trying to figure out the best way to align the CheckBox with the Field.
I can't see a "nice" way to do what you want: the best I can come up with is to separate the label from the check box, and register a mouse listener with the label to toggle the state of the check box. Maybe someone else can see a more elegant way to do this.
SSCCE:
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
public class AlignedCheckBox extends Application {
#Override
public void start(Stage primaryStage) {
GridPane grid = new GridPane();
Label checkboxLabel = new Label("Selected:");
CheckBox checkBox = new CheckBox();
checkboxLabel.setLabelFor(checkBox);
checkboxLabel.setOnMouseClicked(e -> checkBox.setSelected(! checkBox.isSelected()));
Label textFieldLabel = new Label("Enter text:");
TextField textField = new TextField();
grid.addRow(0, checkboxLabel, checkBox);
grid.addRow(1, textFieldLabel, textField);
ColumnConstraints leftCol = new ColumnConstraints();
leftCol.setHalignment(HPos.RIGHT);
leftCol.setHgrow(Priority.SOMETIMES);
ColumnConstraints rightCol = new ColumnConstraints();
rightCol.setHalignment(HPos.LEFT);
rightCol.setHgrow(Priority.ALWAYS);
grid.getColumnConstraints().addAll(leftCol, rightCol);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20));
Scene scene = new Scene(grid);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}