JavaFX fit an image in a toggleButton - javafx

I have the following code
Image img = new Image(getClass().getResource("1.png").toExternalForm(), tg.getWidth(), tg.getHeight(), false, true, true);
ImageView view = new ImageView(img);
tg.setGraphic(view);
(where tg is a toggle button)
and I get this
I want the image to fit perfectly into the button but whatever I do I'm unable to accomplish this. I've already tried using view.setFit methods but it doesn't seem to have any effect
Edit:
This is the code that creates the GridPane
this.gameBoard = new GridPane();
this.gameBoard.setPrefSize(600, 600);
this.gameCards = new ToggleButton[this.boardSize * this.boardSize];
EventHandler<ActionEvent> cardSelectedHandler = this::onCardSelected;
for (int i = 0; i < this.gameCards.length; i++) {
this.gameCards[i] = new ToggleButton;
this.gameCards[i].setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
this.gameCards[i].setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
this.gameCards[i].setOnAction(cardSelectedHandler);
this.gameBoard.add(this.gameCards[i], i % this.boardSize, i / this.boardSize);
GridPane.setHgrow(this.gameCards[i], Priority.ALWAYS);
GridPane.setVgrow(this.gameCards[i], Priority.ALWAYS);
}
private void onCardSelected(ActionEvent event) {
ToggleButton tg = (ToggleButton) event.getTarget();
Image img = new Image(getClass().getResource("1.png").toExternalForm(), tg.getWidth(), tg.getHeight(), false, true, true);
ImageView view = new ImageView(img);
tg.setGraphic(view);
EDIT 2:
doing some change
private void onCardSelected(ActionEvent event) {
ToggleButton tg = (ToggleButton) event.getTarget();
Image img = new Image(getClass().getResource("1.png").toExternalForm());
ImageView view = new ImageView(img);
view.setFitHeight(150);
view.setFitWidth(150);
view.setPreserveRatio(false);
tg.setAlignment(Pos.TOP_LEFT);
tg.setGraphic(view);
I now get
but I still get this button resize

Related

How do I make my buttons all the same size?

Sorry, I have just begun learning javaFX and cannot figure out how to get all of my icons on buttons the same size. I tried a couple things but could not get it working, all help is appreciated. Thank you!
Wont let me post my question unless I add more details but I cant think of anything else to put so just ignore this whole paragraph as I ramble on so I can post my question and continue coding my game.
public class Main extends Application {
Stage window;
Button button;
Scene scene1, scene2;
public static final int ROCK = 0;
public static final int PAPER = 1;
public static final int SCISSORS = 2;
public static int userChoice;
public static void main(String [] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
window = primaryStage;
//Layout 1
VBox layout = new VBox(20);
Label label = new Label("Rock Paper Scissors");
Button myButton = new Button("Start");
myButton.setOnAction(e -> window.setScene(scene2));
Button exit = new Button("Exit");
exit.setOnAction(e -> System.exit(0));
layout.getChildren().addAll(label, myButton, exit);
layout.setAlignment(Pos.CENTER);
scene1 = new Scene(layout, 300, 300);
//Layout 2
BorderPane border = new BorderPane();
VBox layout1 = new VBox(10);
Label label1 = new Label("Choose One");
layout1.setAlignment(Pos.CENTER);
//Layout 3
HBox layout2 = new HBox(10);
//Rock Image Button
Image rockIm = new Image(getClass().getResourceAsStream("Rock2.png"));
Button rock = new Button();
rock.setGraphic(new ImageView(rockIm));
rock.setOnAction(e -> userChoice = ROCK);
//Paper Image Button
Image paperIm = new
Image(getClass().getResourceAsStream("Paper2.png"));
Button paper = new Button();
paper.setGraphic(new ImageView(paperIm));
paper.setOnAction(e -> userChoice = PAPER);
//Scissor Image Button
Image scissorIm = new
Image(getClass().getResourceAsStream("Scissor2.png"));
Button scissors = new Button();
scissors.setGraphic(new ImageView(scissorIm));
scissors.setOnAction(e -> userChoice = SCISSORS);
Button quit = new Button("Return");
quit.setOnAction(e -> window.setScene(scene1));
layout2.getChildren().addAll(rock, paper, scissors, quit);
layout2.setAlignment(Pos.CENTER);
scene2 = new Scene(layout2, 300, 300);
window.setTitle("Rock Paper Scissors");
window.setScene(scene1);
window.show();
}
}

Moving Co-Ordinates of JavaFX text label recursively

My program takes a user value and passes the value through a method before returning a message on the GUI. I am wondering how I could be able to recursively move this message (called displayResult) value down along the Y axis in order to make room for new messages when the user calls the method again.
public class GuessingGameController extends Tab {
Scene sceneOne;
Scene sceneTwo;
int choice;
int generatedNumber;
//private GuessingGame resetGuessingGame;
public int generateRandomNumber() {
Random randomNumber = new Random();
int number = randomNumber.nextInt(50) + 1;
return number;
}
GuessingGameController(Stage primaryStage) {
GuessingGame guess = new GuessingGame();
generatedNumber = generateRandomNumber();
Label labelOne = new Label("WELCOME TO THE GUESSING GAME");
setText("GuessingGame");
Pane paneLayoutOne = new StackPane();
Pane paneLayoutTwo = new StackPane();
Button playButton = new Button("Click to Play!");
Button quitButton = new Button("Quit");
paneLayoutOne.getChildren().addAll(labelOne, playButton, quitButton);
labelOne.setTranslateX(0);
labelOne.setTranslateY(-100);
playButton.setTranslateX(0);
playButton.setTranslateY(0);
quitButton.setTranslateX(0);
quitButton.setTranslateY(50);
setContent(paneLayoutOne);
sceneOne = new Scene(paneLayoutOne, 400, 400);
quitButton.setOnAction(e -> System.exit(0));
playButton.setOnAction(e -> primaryStage.setScene(sceneTwo));
Label userMessage = new Label("Please enter your guess here");
TextField userInput = new TextField();
Button guessButton = new Button("Guess");
Button resetButton = new Button("Reset Game");
Button backButton = new Button("Back");
userMessage.setTranslateX(0);
userMessage.setTranslateY(-160);
userInput.setTranslateX(0);
userInput.setTranslateY(-120);
guessButton.setTranslateX(0);
guessButton.setTranslateY(-80);
resetButton.setTranslateX(0);
resetButton.setTranslateY(-40);
backButton.setTranslateX(0);
backButton.setTranslateY(0);
guessButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
int choice = Integer.parseInt(userInput.getText());
guess.startGuessingGame(choice, generatedNumber);
String endResult;
endResult = guess.startGuessingGame(choice, generatedNumber);
Label displayResult = new Label(endResult);
displayResult.setTranslateX(0);
displayResult.setTranslateY(150);
paneLayoutTwo.getChildren().add(0, displayResult);
}
});
//resetButton.setOnAction(e -> resetGuessingGame.resetForm(this));
backButton.setOnAction(e -> primaryStage.setScene(sceneOne));
paneLayoutTwo.getChildren().addAll(userMessage, userInput, guessButton, resetButton, backButton);
sceneTwo = new Scene(paneLayoutTwo, 400, 400);
}
}

Gluon Mobile Toggle Button Jumping

I'm trying to implement a Gluon Mobile toggle button for a survey page, and when testing, the button jumps to the left a little when I click it. I don't want it to jump at all. You can see it here:
Relevant code is here:
StackPane getToggler() {
ToggleButton toggleButton = new ToggleButton("Yes");
ToggleButtonGroup toggleButtonGroup = new ToggleButtonGroup();
toggleButtonGroup.setSelectionType(SelectionMode.SINGLE);
toggleButtonGroup.setPadding(new Insets(10));
toggleButton = new ToggleButton("Yes");
toggleButton.setStyle("-fx-text-fill:steelblue;");
toggleButton.setUserData("1");
toggleButton.setSelected(false);
toggleButton.selectedProperty().addListener((obv, ov, nv) -> {
if (nv.booleanValue()) {
toggleButtonGroup.setUserData("1");
}
});
toggleButtonGroup.getToggles().add(toggleButton);
toggleButton = new ToggleButton("No");
toggleButton.setStyle("-fx-text-fill:steelblue;");
toggleButton.setSelected(true);
toggleButton.setUserData("0");
toggleButton.setSelected(false);
toggleButton.selectedProperty().addListener((obv, ov, nv) -> {
if (nv.booleanValue()) {
toggleButtonGroup.setUserData("0");
}
});
toggleButtonGroup.getToggles().add(toggleButton);
togglers.add(toggleButtonGroup);
StackPane wrapper = new StackPane();
wrapper.setAlignment(Pos.CENTER);
wrapper.getChildren().add(toggleButtonGroup);
return wrapper;
}
Here's where I get the togglers and their relation to the label to the left:
for (int i = 0; i < this.questions.length; i++) {
HBox row = new HBox();
row.setSpacing(5);
row.setAlignment(Pos.CENTER_LEFT);
Label label = new Label(this.questions[i]);
label.setWrapText(true);
label.setPrefWidth(200);
label.setTextAlignment(TextAlignment.LEFT);
label.setFont(new Font("System", 14));
StackPane wrapper = this.getToggler();
Region region = new Region();
HBox.setHgrow(region, Priority.ALWAYS);
HBox.setHgrow(label, Priority.NEVER);
row.getChildren().addAll(label,region,wrapper);
box.getChildren().add(row);
box.getChildren().add(new Separator());
}
After some debugging, I've realized that the min width value of the toggle buttons is wider than their pref width.
This means that after the user selects one toggle, the min width is applied, and the control is resized with the required min width, shrinking the region as a consequence.
A quick fix (until this gets fixed in the control) can be setting the min width of your toggle buttons:
private StackPane getToggler() {
ToggleButtonGroup toggleButtonGroup = new ToggleButtonGroup();
ToggleButton toggleButtonYes = new ToggleButton("Yes");
toggleButtonYes.minWidthProperty().bind(toggleButtonYes.prefWidthProperty());
toggleButtonGroup.getToggles().add(toggleButtonYes);
ToggleButton toggleButtonNo = new ToggleButton("No");
toggleButtonNo.minWidthProperty().bind(toggleButtonNo.prefWidthProperty());
toggleButtonGroup.getToggles().add(toggleButtonNo);
...;
}

Set image on left side of dialog

I created this very simple example for JavaFX alert dialog for JavaFX8u40.
public class MainApp extends Application
{
public static void main(String[] args)
{
Application.launch(args);
}
private Stage stage;
#Override
public void start(Stage primaryStage) throws Exception
{
Button create = new Button("Create Alert");
create.setTooltip(new Tooltip("Create an Alert Dialog"));
create.setOnAction(e ->
{
createAlert();
});
primaryStage.setScene(new Scene(create));
primaryStage.show();
stage = primaryStage;
}
protected Alert createAlert()
{
Alert alert = new Alert(AlertType.WARNING);
Image image1 = new Image("http://www.mcaprojecttraining.com/images/java-big-icon.png");
ImageView imageView = new ImageView(image1);
alert.setGraphic(imageView);
alert.initModality(Modality.APPLICATION_MODAL);
alert.initOwner(stage);
alert.getDialogPane().setContentText("Some text");
alert.showAndWait()
.filter(response -> response == ButtonType.OK)
.ifPresent(response -> System.out.println("The alert was approved"));
return alert;
}
}
I'm interested how I can set the image on the left side of the dialog.
Did someone manage to change the side of the image?
If you have a look at how the header is constructed, you'll find a GridPane node to layout a Label on the left and a StackPane for the icon.
If you want to reverse the cells order by code, you can do it, but it will be overriden every time updateHeaderArea() is called.
My suggestion is using this public API:
dialogPane.setHeader(Node header);
dialogPane.setGraphic(Node graphic);
providing a header with an icon on the left and a label, and a null graphic.
Using the same approach as DialogPane, we could add another GridPane as header:
protected Alert createAlert(){
Alert alert = new Alert(AlertType.WARNING);
alert.initModality(Modality.APPLICATION_MODAL);
alert.initOwner(stage);
alert.getDialogPane().setContentText("Some text");
DialogPane dialogPane = alert.getDialogPane();
GridPane grid = new GridPane();
ColumnConstraints graphicColumn = new ColumnConstraints();
graphicColumn.setFillWidth(false);
graphicColumn.setHgrow(Priority.NEVER);
ColumnConstraints textColumn = new ColumnConstraints();
textColumn.setFillWidth(true);
textColumn.setHgrow(Priority.ALWAYS);
grid.getColumnConstraints().setAll(graphicColumn, textColumn);
grid.setPadding(new Insets(5));
Image image1 = new Image("http://www.mcaprojecttraining.com/images/java-big-icon.png");
ImageView imageView = new ImageView(image1);
imageView.setFitWidth(64);
imageView.setFitHeight(64);
StackPane stackPane = new StackPane(imageView);
stackPane.setAlignment(Pos.CENTER);
grid.add(stackPane, 0, 0);
Label headerLabel = new Label("Warning");
headerLabel.setWrapText(true);
headerLabel.setAlignment(Pos.CENTER_RIGHT);
headerLabel.setMaxWidth(Double.MAX_VALUE);
headerLabel.setMaxHeight(Double.MAX_VALUE);
grid.add(headerLabel, 1, 0);
dialogPane.setHeader(grid);
dialogPane.setGraphic(null);
alert.showAndWait()
.filter(response -> response == ButtonType.OK)
.ifPresent(response -> System.out.println("The alert was approved"));
return alert;
}
And this is what you will see:

How to display number of lines textarea javafx

I´m trying to create a list with the number of lines of a textarea like in a text editor. I have done it with a VBox item and adding TextField ListCell but when I scroll in the textarea, the VBox doesn´t it . How can I do it?. This is part of code:
TextArea areaNueva = new TextArea();
areas.add(numeroTab, areaNueva);
areas.get(numeroTab).setStyle("-fx-font:15pt \"Times New Roman\";" + "-fx-focus-color: transparent;");
BorderPane bor = new BorderPane();
ObservableList<TextFieldListCell> tf = FXCollections.observableArrayList();
TextFieldListCell cell = new TextFieldListCell();
VBox b = new VBox();
cell.setPrefSize(20,1);
cell.setFont(Font.font("Times New Roman",11.35));
cell.setText("1");
tf.add(0,cell);
b.getChildren().addAll(tf);
b.setSpacing(-2);
b.setPadding(new Insets(3,0,0,0));
bor.setLeft(b);
bor.setCenter(areaNueva);
Tab tabNuevo = new Tab("Sin Titulo");
tabs.add(numeroTab, tabNuevo);
tabs.get(numeroTab).setClosable(true);
tabs.get(numeroTab).setContent(bor);
An with this I add new number of lines:
private ArrayList<ObservableList<TextFieldListCell>> lineas = new ArrayList<ObservableList<TextFieldListCell>>();
String parte = null;
int i = 1;
while ((parte = br.readLine()) != null) {
areaAUtilizar.appendText(parte + "\n");
if(i!=1){
TextFieldListCell c = new TextFieldListCell();
c.setText(Integer.toString(i));
c.setFont(Font.font("Times New Roman",11.35));
c.setPrefSize(20, 13);
lineas.get(a).add(i-1,c);
boxes.get(a).getChildren().setAll(lineas.get(a));
}
i++;
}
I solved it by removing the scroll of the textarea and the listview and put its opacity to 0, and putting both in a borderpane. After I put a scrollbar and the borderpane in a scrollpane. And for it to appear the scrollbar of the scrollpane I increased the height of the textarea and the listview when the lines of the textarea are more great than the prefheight.

Resources