I'm trying to make a window with a certain layout using 2 columns, but I can't quite get it to work the way I want.
First, some simplified example code:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Spinner;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class GridTest extends Application {
@Override
public void start(final Stage stage) throws Exception {
final GridPane grid = new GridPane();
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10, 10, 10, 10));
grid.add(new Label("Something:"), 0, 0);
final Spinner<?> s1 = new Spinner<>();
grid.add(s1, 1, 0);
grid.add(new Label("Another thing:"), 0, 1);
final Spinner<?> s2 = new Spinner<>();
grid.add(s2, 1, 1);
final Button b = new Button("A button");
grid.add(b, 0, 2, 2, 1);
stage.setScene(new Scene(grid, 400, 150));
stage.show();
}
public static void main(final String... args) {
launch(args);
}
}
Here is what I want:
I tried using all sorts of constraints, but I couldn't get everything to work right. I think the main problem I found was that after getting the spinners to use the available width, they refused to shrink when narrowing the window.
I'm using Oracle JDK 1.8.0_60 in Linux.
This seems to be a Spinner
bug , I'm getting much better results if I use TextField
s instead.
Example:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
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 GridTest extends Application {
@Override
public void start(final Stage stage) throws Exception {
final GridPane grid = new GridPane();
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10, 10, 10, 10));
ColumnConstraints cc = new ColumnConstraints();
cc.setMinWidth(GridPane.USE_PREF_SIZE);
grid.getColumnConstraints().add(cc);
cc = new ColumnConstraints();
cc.setMinWidth(GridPane.USE_PREF_SIZE);
cc.setHgrow(Priority.ALWAYS);
grid.getColumnConstraints().add(cc);
grid.add(new Label("Something:"), 0, 0);
final TextField t1 = new TextField();
grid.add(t1, 1, 0);
grid.add(new Label("Another thing:"), 0, 1);
final TextField t2 = new TextField();
grid.add(t2, 1, 1);
final Button b = new Button("A button");
b.setMaxWidth(Double.MAX_VALUE);
grid.add(b, 0, 2, 2, 1);
stage.setScene(new Scene(grid, 400, 150));
stage.show();
}
public static void main(final String... args) {
launch(args);
}
}
But replace the TextField
s with Spinner
s and all hell breaks loose...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.