Invalid Image url - java

I can't seem to use the Image class. My colleague and I are working on a project together and he seems to be able to run all the code fine without any errors. When I try to run the same code, with the src organized the same way, I get an invalid URL or resource not found error. I have had this problem on other projects and it seems like it is specific to my computer or file system. Any help would be much appreciated. Here is a sample of the code.
public class HomePageGUI extends Application {
//Create the dispenser. Generates 5 Products in an array within the dispenser class.
private final Dispenser dispenser = new Dispenser();
//Get background image and add it to the stack pane
private final Image bgImage = new Image("/Dispenser Design/Background & Button Images/Background.png");
private final Button backButton = new Button("", new ImageView(
new Image("/Dispenser Design/Background & Button Images/Navigation Buttons/Back Button.png")));
private StackPane backgroundPane = new StackPane();
private Scene scene;
#Override
public void start(Stage primaryStage) {
primaryStage = homePage(primaryStage);
primaryStage.show();
}
//Display the home page
private Stage homePage(Stage stage) {
//IMAGE CREATION
Image drinksCategoryImage = new Image (
"/Dispenser Design/Background & Button Images/Starter Page/Drinks Button.png");
Image gumCategoryImage = new Image (
"/Dispenser Design/Background & Button Images/Starter Page/Gum Button.png");
Image sweetsCategoryImage = new Image (
"/Dispenser Design/Background & Button Images/Starter Page/Sweets Button.png");
//END IMAGE CREATION
//Create the buttons with the image displayed on them.
Button drinksCategoryButton = new Button(
"", new ImageView(drinksCategoryImage));
drinksCategoryButton.setOnAction(e -> {
drinksCategory(stage); });
Button gumCategoryButton = new Button(
"", new ImageView(gumCategoryImage));
gumCategoryButton.setOnAction(e -> {
gumCategory(stage); });
Button sweetsCategoryButton = new Button(
"", new ImageView(sweetsCategoryImage));
sweetsCategoryButton.setOnAction(e -> {
sweetsCategory(stage); });
//END BUTTON CREATION

Ok so after many hours of troubleshooting I figured out that I needed to add file: to the image path. I am not sure why my colleagues did not need to add the file: extension to make the images work, but that is how it ended up working for me.
productsForSale[ 4] = new Gum("Wriggleys", "Big Red", .75, 1, new Image(
"file:src/DispenserDesign/IndividualProducts/BigRedGum.jpg"));

Related

JavaFX button set image

I am trying to set an image to a button but I can't get a working result.
My button is located in gridpane.
Image mine = new Image(new File("..some path").toURI().toString());
ImageView im = new ImageView(mine);
im.setFitHeight(btn.getHeight());
im.setFitWidth(btn.getWidth());
btn.setGraphic(im);
How can I do this?
I'm trying add to panel, but sometimes button was removed and I didnt get button with image.
private static void setFlag(Button btn,int x,int y,GridPane gridPane){
Image mine = new Image(new File("some path..").toURI().toString());
ImageView im = new ImageView(mine);
im.setFitHeight(btn.getHeight());
im.setFitWidth(btn.getWidth());
btn.setGraphic(im);
gridPane.add(btn, y, x);
}
This method is called when a button is pressed. Before that I used another method, where I used label and this method worked.
private static void setBombCell(Button btn, int x,int y,GridPane gridPane){
Image mine = new Image(new File("..").toURI().toString());
ImageView im = new ImageView(mine);
Label label = new Label();
label.setMaxWidth(Double.MAX_VALUE);
label.setMaxHeight(Double.MAX_VALUE);
GridPane.setHgrow(label, Priority.ALWAYS);
GridPane.setVgrow(label, Priority.ALWAYS);
im.setFitHeight(btn.getHeight());
im.setFitWidth(btn.getWidth());
label.setGraphic(im);
gridPane.add(label, y, x);
}
I solved this problem. I used method button.setStyle("") for this.

JavaFX New Scene on Button Click

The title may be a bit vague, so allow me to define it a little better. I have a working piece of code (down below): a simple main menu for a game I am working on. Everything works well, except for the Start button.
What I want to be able to do is click the Start button, and have a new scene appear on the same stage (window). I do not want to see a new window open. I have talked with someone more experienced in Java, and they told me to create separate classes for the MenuFX and the GameFX. If that is the case, I would need to call some start or launch method on the GameFX class from the MenuFX class, correct? Is this the best approach, or would I want to keep all FX-related code in one class? Also, I should keep the same stage for all FX work, no?
This post shed some light on things, but I am not well-versed in some of the terms discussed- for instance, I still do not understand the concept of Root.
Also, this post talks about a similar application, but I am not using FXML or SceneBuilder... I do not know if any of it is relatable.
MenuFX.java - I have removed some of the working code, simply for brevity. You can see that all I need help with is tying the Start button to some functionality that makes a new empty scene.
/*
* This is simply working on the title screen.
*/
// Asssume all imports are correct
import java.everythingNeeded
public class MenuFX extends Application {
#Override
public void start (Stage primaryStage) {
// Make the window a set size...
primaryStage.setResizable(false);
// Create menu vbox and set the background image
VBox menuVBox = new VBox(30);
menuVBox.setBackground(new Background(new BackgroundImage(new
Image("image/bambooBG.jpg"), null, null, null, new BackgroundSize(45,
45, true, true, true, true))));
// Create start button
Button startButton = new Button("Start Game");
// TODO Some things...
// Need assistance here
// Create help button
Button helpButton = new Button("Help");
helpButton.setOnAction(e -> THINGS);
// Create music toggle button
ToggleButton musicButton = new ToggleButton("Music On/Off");
musicButton.setOnAction(e -> THINGS);
// Create credits button
Button creditsButton = new Button("Credits");
creditsButton.setOnAction(THINGS);
// Create exit button and set it to close the program when clicked
Button endButton = new Button("Exit Game");
endButton.setOnAction(e -> Platform.exit());
// Add all nodes to the vbox pane and center it all
// Must be in order from top to bottom
menuVBox.getChildren().addAll(startButton, helpButton, musicButton, creditsButton, endButton);
menuVBox.setAlignment(Pos.CENTER);
// New scene, place pane in it
Scene scene = new Scene(menuVBox, 630, 730);
// Place scene in stage
primaryStage.setTitle("-tiles-");
primaryStage.setScene(scene);
primaryStage.show();
}
// Needed to run JavaFX w/o the use of the command line
public static void main(String[] args) {
launch(args);
}
}
Restating: I want to click the Start button and have the currently open window change to an empty scene.
Here is a pastebin of the MenuFX class in its entirety:
http://pastebin.com/n6XbQfhc
Thank you for any help,
Bagger
The basic idea here is you would do something like:
public class GameFX {
private final BorderPane rootPane ; // or any other kind of pane, or Group...
public GameFX() {
rootPane = new BorderPane();
// build UI, register event handlers, etc etc
}
public Pane getRootPane() {
return rootPane ;
}
// other methods you may need to access, etc...
}
Now back in the MenuFX class you would do
Button startButton = new Button("Start Game");
startButton.setOnAction(e -> {
GameFX game = new GameFX();
primaryStage.getScene().setRoot(game.getRootPane());
});

Javafx: instance label not displayed

I am new in Javafx (and Java).
I am trying to display a label "title" to different scenes. Therefore this label in a instance variable. I create it using the method title().
The problem is that the title does not appear in my scenes. I tried to initialize it at class level, or inside the start(), or inside scene1(). Nothing works but when I create a local label inside the scene1() method.
Thanks in advance for your help.
ps: full repo here if needed
private Label title;
public void start(Stage primaryStage) {
title();
scene1();
scene2();
[some more code...]
}
public Node title() {
title = new Label();
title.setText("SNAKE");
title.setTextFill(Color.YELLOW);
title.setFont(Font.font(STYLESHEET_MODENA, FontWeight.BOLD, 80));
return title;
}
public Scene scene1() {
Label lbl1scene1 = new Label("Welcome to Game !");
Label lbl2scene1 = new Label("Click to start the game");
Button btnStart = new Button("Start the game now!");
btnStart.setOnAction(e -> {
runGame();
});
VBox vbox1 = new VBox(title, lbl1scene1, lbl2scene1, btnStart);
vbox1.setAlignment(Pos.CENTER);
vbox1.setSpacing(10);
scene1 = new Scene(vbox1, width, height);
return scene1;
}
I am trying to display a label "title" to different scenes.
Please note that a node can have only a single parent.
Create multiple instances using local variables instead of a title member field.

JavaFX let user set a picture

So
I am trying to let the user set a path to a picture and then display it but I am not able to display it.
Currently, I am using Eclipse and Scene Builder to accomplish my goals
Code so far:
#FXML
public void choseFile() {
fc = new FileChooser();
File tmp = fc.showOpenDialog(dialogStage);
Image img = new Image(tmp.getAbsolutePath);
image1 = new ImageView();
image1.setImage(img);
}
image1 is set to an ImageView in the SceneBuilder and the choseFile() method is set to a button that is next to that picture
Thanks in advance
As James_D mentioned, you need to add ImageView in your code.
Import javax.scene.image.ImageView.
According to the documentation,
The ImageView is a Node used for painting images loaded with Image class. This class allows resizing the displayed image (with or without preserving the original aspect ratio) and specifying a viewport into the source image fro restricting the pixels displayed by this ImageView.
Sample code from the document :
public class HelloMenu extends Application {
#Override public void start(Stage stage) {
// load the image
Image image = new Image("flower.png");
// simple displays ImageView the image as is
ImageView iv1 = new ImageView();
iv1.setImage(image);
// resizes the image to have width of 100 while preserving the ratio and using
// higher quality filtering method; this ImageView is also cached to
// improve performance
ImageView iv2 = new ImageView();
iv2.setImage(image);
iv2.setFitWidth(100);
iv2.setPreserveRatio(true);
iv2.setSmooth(true);
iv2.setCache(true);
// defines a viewport into the source image (achieving a "zoom" effect) and
// displays it rotated
ImageView iv3 = new ImageView();
iv3.setImage(image);
Rectangle2D viewportRect = new Rectangle2D(40, 35, 110, 110);
iv3.setViewport(viewportRect);
iv3.setRotate(90);
Group root = new Group();
Scene scene = new Scene(root);
scene.setFill(Color.BLACK);
HBox box = new HBox();
box.getChildren().add(iv1);
box.getChildren().add(iv2);
box.getChildren().add(iv3);
root.getChildren().add(box);
stage.setTitle("ImageView");
stage.setWidth(415);
stage.setHeight(200);
stage.setScene(scene);
stage.sizeToScene();
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}

Resize menu into layer

I have this JavaFX menu which is not working properly:
public class CreatingMenus {
// Generate Menu
public void initMenu(Stage primaryStage, Group root, Scene scene) {
// Call Menu Actions from Java Method MenuActions
final MenuActions ma = new MenuActions();
MenuBar menuBar = new MenuBar();
// File menu - new, save, close, exit
Menu menu = new Menu("File");
menu.getItems().add(new MenuItem("New"));
menu.getItems().add(new MenuItem("Save"));
menu.getItems().add(new MenuItem("Close"));
menu.getItems().add(new SeparatorMenuItem());
MenuItem menuItem = new MenuItem("Exit");
// Exit from the application
menuItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
// This Java Method is called from the Java Class MenuActions
ma.programExit(); // Exit program
}
});
menu.getItems().add(menuItem);
menuBar.getMenus().add(menu);
// Options menu - Preferences
Menu options = new Menu("Options");
options.getItems().add(new MenuItem("Preferences"));
menuBar.getMenus().add(options);
// Help menu - About
Menu help = new Menu("Help");
MenuItem helpItem = new MenuItem("About");
// Exit from the application
helpItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
aboutDialog();
}
});
help.getItems().add(helpItem);
menuBar.getMenus().add(help);
menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
menuBar.setLayoutX(0);
menuBar.setLayoutY(0);
root.getChildren().add(menuBar);
}
public void aboutDialog() {
final int xSize = 640;
final int ySize = 480;
final String logoImage = "/logo.png";
final Color backgroundColor = Color.WHITE;
final String text = "SQL Browser";
final String version = "Product Version: 1.0";
final String license = "License Information";
final Stage aboutDialog = new Stage();
aboutDialog.initModality(Modality.WINDOW_MODAL);
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 20, 20, 20));
// Logo
Image image = new Image(getClass().getResourceAsStream(logoImage));
ImageView logo = new ImageView(image);
grid.add(logo, 1, 0);
// Product name
Text productName = new Text(text);
productName.setFont(Font.font("Verdana", 12));
grid.add(productName, 0, 2);
// Product version
Text productVersion = new Text(version);
productVersion.setFont(Font.font("Verdana", 12));
grid.add(productVersion, 0, 3);
// Product License
Text productLicense = new Text(license);
productLicense.setFont(Font.font("Verdana", 12));
grid.add(productLicense, 0, 4);
// Close Button
Button closeButton = new Button("Close");
closeButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
// Close the dialog when "Close" button is pressed
aboutDialog.close();
}
});
grid.add(closeButton, 5, 18);
// Configure dialog size and background color
Scene aboutDialogScene = new Scene(grid, xSize, ySize, backgroundColor);
aboutDialog.setScene(aboutDialogScene);
aboutDialog.show();
}
}
When I add this menu it overrides the other components into the application and they are not responsible because I suppose they are behind this layer. Can you tell how I can isolate this menu in separate layer because I don't want to place other components behind.
EDIT
When I use the menu code I get this result:
When I remove the the menu code I get this result and the application is working properly:
The problem somewhere into the menu code.
Scene Width Binding
Stage width contains window borders and a title bar - which are irrelevant to internal layout.
To fill the scene width with something using binding, bind the preferred size of the thing to a scene size and not the stage size:
menuBar.prefWidthProperty().bind(menuBar.getScene().widthProperty());
Or (usually preferred) you can use alternate layout panes and layout constraints which perform the sizing automatically. For your particular layout a BorderPane might be useful.
You may have additional issues with your implementation which cause problems (I have not checked).
Using Groups for Layout
Your pastebin code uses a Group for the main scene layout root. Group is generally a poor choice for laying out a flexibly sized screen like your example. A group is not re-sizable. Instead it is advisable to use a re-sizable layout pane as referred to above.
Tool Support
ScenicView is invaluable in debugging existing layout issues.
SceneBuilder is great for rapid prototyping of various layouts.
I strongly advise using these tools to help understand how layouts work and to provide you with the tools and knowledge you need to debug layout issues yourself.
Works for me without any changes. You might should check your Java/JavaFx versions. I am using 1.7_17, 64 bits on windows.
I have added some images (I don't have yours) to get sure the behaviour you get is not because of them.

Categories