0

I'm creating a Java Application which lets the User click a button that opens a File Selector and upon selecting an image creates a Button with that image and text from a Text Field. It's working without the image but I can't figure out how to add an image to the button for the life of me.

Context: btns is a GridPane of Buttons, lastTopIn is an integer that keeps track of the last used column of the GridPane. The button removes itself when clicked.

FileChooser fc = new FileChooser()
fc.setTitle("Choose Image for Button");
File file = fc.showOpenDialog(null);
lastTopIn++;
Button thebutton = new Button((String) tf.getText(), new ImageView(new Image(getClass().getResourceAsStream("file://"+file.getAbsolutePath()))));
    thebutton.setOnMouseClicked(new EventHandler<Event>() {
        @Override
        public void handle(Event event) {
            btns.getChildren().remove(thebutton);                           
        }
    });
btns.add(thebutton, lastTopIn,1);

Thanks in advance for any help.

4
  • I think this is wrong getClass().getResourceAsStream("file://"+file.getAbsolutePath()). Not 100% sure though. Commented Mar 20, 2018 at 19:35
  • 1
    Off-topic: don't use setOnMouseClicked on a button; use setOnAction instead. Commented Mar 20, 2018 at 19:46
  • @James_D Where's the difference? Commented Mar 20, 2018 at 20:40
  • @LW001 The difference will be pretty important if the user tries to trigger the button with the keyboard. Commented Mar 20, 2018 at 20:41

1 Answer 1

1

To display an image from a file on the file system, convert the file to a URI, instead of trying to load it as a resource:

Button thebutton = new Button(tf.getText(), 
    new ImageView(new Image(file.toURI().toString())));

file.ToURI() will create the correct URI scheme, as well as properly escaping any characters such as whitespace that are legal in filenames but illegal in URIs.

Note that, as a shortcut, you can pass the URI directly to the ImageView constructor, and it will create the image for you:

Button thebutton = new Button(tf.getText(), new ImageView(file.toURI().toString()));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.