How do I make my buttons all the same size? - javafx

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();
}
}

Related

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);
}
}

Allow clicks to go through application GUI

I have a JavaFx application that loads a transparent stage with some text on it.
I want any click on the application to be completely ignored and the background application (if any) to receive that click.
My code at this stage is as follows:
public void start(final Stage primaryStage) {
primaryStage.setAlwaysOnTop(true);
final StackPane layout = new StackPane();
final Text mainText = new Text();
layout.getChildren().add(mainText);
mainText.setText("|||||||||||||||||||||||||||");
final Scene mainScene = new Scene(layout);
mainScene.setFill(null);
primaryStage.initStyle(StageStyle.TRANSPARENT);
primaryStage.setScene(mainScene);
primaryStage.show();
layout.setMouseTransparent(true);
mainText.setMouseTransparent(true);
}
I was not able to achieve the requirement. setMouseTransparent() just prevented the text from triggering events, it still captured the mouse clicks.
Is it possible to achieve this in JavaFx ? Even if it is a per-OS solution.
A way of doing this action in Windows is through user32.dll and Java Native Access (JNA). We used GetWindowLong to get the current configuration of the window and SetWindowLong to update the bit field that is controlling the ability of the window be transparent to the mouse.
Following is a working example that demonstrates this functionality:
#Override
public void start(final Stage primaryStage) {
primaryStage.setAlwaysOnTop(true);
final StackPane layout = new StackPane();
final Text mainText = new Text();
layout.getChildren().add(mainText);
mainText.setText("|||||||||||||||||||||||||||");
final Scene mainScene = new Scene(layout);
mainScene.setFill(null);
primaryStage.initStyle(StageStyle.TRANSPARENT);
primaryStage.setScene(mainScene);
primaryStage.setTitle(sTitle);
primaryStage.show();
sUser32.EnumWindows(
(hWnd, data) -> {
final byte[] windowText = new byte[512];
sUser32.GetWindowTextA(hWnd, windowText, 512);
final String wText = Native.toString(windowText);
if (!wText.isEmpty() && wText.equals(sTitle)) {
final int initialStyle = com.sun.jna.platform.win32.User32.INSTANCE.GetWindowLong(hWnd, WinUser.GWL_EXSTYLE);
com.sun.jna.platform.win32.User32.INSTANCE.SetWindowLong(hWnd, WinUser.GWL_EXSTYLE, initialStyle | WinUser.WS_EX_TRANSPARENT );
return false;
}
return true;
}, null);
}

How can I assign an EventListener to a Path in javafx?

I have this piece of code which doesn't work correctly.
I want to set a listener for when a user clicks inside the square, yet
neither the pop-up nor the message "clicked" are displayed when I click
inside the square.
What am I missing?
This method is inside the Coords class.
public static void drawMyShape(final GraphicsContext ctx) {
Path path = new Path();
MoveTo mT = new MoveTo();
LineTo lT[] = new LineTo[4];
mT.setX(200.0);
mT.setY(200.0);
lT[0] = new LineTo(400.0, 200.0);
lT[1] = new LineTo(400.0, 400.0);
lT[2] = new LineTo(200.0, 400.0);
lT[3] = new LineTo(200.0, 200.0);
path.setStroke(Color.BEIGE);
path.getElements().addAll(mT, lT[0], lT[1], lT[2], lT[3]);
path.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(Main.prim_stage);
VBox box = new VBox(20);
box.getChildren().add(new Text("Hey"));
Scene s = new Scene(box, 300, 200);
dialog.setScene(s);
dialog.show();
System.out.println("Clicked");
}
});
ctx.setLineWidth(4.0);
ctx.beginPath();
ctx.moveTo(mT.getX(), mT.getY());
for (int i = 0; i < lT.length; i++) {
ctx.lineTo(lT[i].getX(), lT[i].getY());
}
ctx.closePath();
ctx.stroke();
}
EDITED ON SUGGESTION by users.
So his is the main program:
public class Main extends Application {
public static Pane root;
private static Canvas main_canvas;
private static GraphicsContext ctx;
private static Rectangle2D bounds;
private static Scene scene;
public static Stage prim_stage;
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Switzerland Advertising");
initElements(primaryStage);
Coords.drawMyShape(ctx);
primaryStage.show();
System.out.println("Launched");
}
public static void main(String[] args) {
launch(args);
}
}
Everything is instanciated inside the following function, which works correctly and displays a full screen application with a canvas and a square drawn into it (image at the bottom).
private void initElements(final Stage primaryStage) {
prim_stage = primaryStage;
// ----------------------------------------
bounds = Screen.getPrimary().getVisualBounds();
double w = bounds.getWidth();
double h = bounds.getHeight();
// ----------------------------------------
// init elements of scene
root = new Pane();
main_canvas = new Canvas(w, h);
// ----------------------------------------
// init scene elements
scene = new Scene(root, w, h);
primaryStage.setX(bounds.getMinX());
primaryStage.setY(bounds.getMinY());
primaryStage.setWidth(w);
primaryStage.setHeight(h);
primaryStage.setScene(scene);
// ----------------------------------------
ctx = main_canvas.getGraphicsContext2D();
// set elements in main pane
root.getChildren().add(main_canvas);
// ----------------------------------------
}
So how can I make the pop-up window appear whenever I click inside the region drawn on the canvas?
This is the program
Your path is just a local variabl within your method. It has to be attached to the scene graph in order to get events. But when you attach it to the scene graph, drawing the same path on a canvas also does not make much sense.

TableView is not visible until click

I am using JavaFX and I have a strange problem. The follwing code is in the constructor of a class, which inherits Stage. The code is work in progress.
// this works fine, the chart is displayed
Scene scene = new Scene(lineChart, 1000, 600);
// table is not shown until I click on the window
Scene scene = new Scene(bidTable, 1000, 600);
this.setTitle("Auction chart");
this.setScene(scene);
What do I wrong? No errors and table with content is shown after I click on the window. Before it's just a white window.
EDIT:
I removed the chart just the table:
public class AuctionChart extends Stage {
private final TableView<Bid> bidTable = new TableView<Bid>();
private final TableColumn<Bid, String> bidColumn = new TableColumn<Bid, String>("Bid");
private final TableColumn<Bid, String> utilityColumn = new TableColumn<Bid, String>("Utility");
private final TableColumn<Bid, String> profitColumn = new TableColumn<Bid, String>("Profit");
private final NumberFormat fm = NumberFormat.getCurrencyInstance();
public AuctionChart() {
initialize();
bidTable.getColumns().addAll(bidColumn, utilityColumn, profitColumn);
Scene scene = new Scene(bidTable, 1000, 600);
this.setTitle("Auction chart");
this.setScene(scene);
}
public void setTowns(List<Town> towns) {
bidTable.setItems(FXCollections.observableArrayList(towns.get(0).getGebote()));
}
private void initialize() {
bidColumn.setCellValueFactory(cellData -> new SimpleStringProperty(fm.format(cellData.getValue().getBid())));
utilityColumn
.setCellValueFactory(cellData -> new SimpleStringProperty(fm.format(cellData.getValue().getUtility())));
profitColumn
.setCellValueFactory(cellData -> new SimpleStringProperty(fm.format(cellData.getValue().getProfit())));
}
}
Startup:
AuctionChart stage = new AuctionChart();
stage.setTowns(towns);
stage.show();
Thank you, it isn't a JavaFx Problem. It's an issue with concurrent threads in the application's backend.

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:

Resources