JavaFX button set image - java

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.

Related

How to set an image to the size of a button in JavaFX

I'm using JavaFX for school and I need to display a picture on a button when I click on it. My problem is that the image is bigger than the button and then everything is horrible. I have seen multiples post on how to fit a image to a button and I came with that code
Image imageOk = new Image(getClass().getResourceAsStream("/TP2/ressources/flag.png"));
ImageView img = new ImageView(imageOk);
img.setFitWidth(100);
img.setFitHeight(100);
btn.setGraphic(img);
When I create the button I use setPrefSize(50, 50);
You can use the fitWidthProperty and fitHeightProperty of the ImageView and bind them to the widthProperty and heightProperty of the button:
img.fitWidthProperty().bind(btn.widthProperty());
img.fitHeightProperty().bind(btn.heightProperty());
This will cause the ImageView to have the same size as the button every time.
This can cause the image to be stretched. To prevent this you can use setPreserveRatio on the image:
img.setPreserveRatio(true);
Here is the complete example code:
Button btn = new Button();
btn.setPrefSize(50, 50);
Image imageOk = new Image(getClass().getResourceAsStream("yes.png"));
ImageView img = new ImageView(imageOk);
img.setPreserveRatio(true);
img.fitWidthProperty().bind(btn.widthProperty());
img.fitHeightProperty().bind(btn.heightProperty());
btn.setGraphic(img);

Invalid Image url

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

BufferedImage on StackPane in JavaFX

I have a BufferedImage and I want to show in a stackpane, because I'm working in JavaFX application.I was in the same situation few day ago, but I was working in Java, in that case I did like this:
public static void VisImmagineDaPc(JFrame frame, BufferedImage image) throws Throwable
{
if (label==null){
label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.AFTER_LAST_LINE);
// frame.setSize(10, 10);
int larghezza = frame.getWidth();
int altezza = frame.getHeight();
// frame.setSize(larghezza, altezza);
frame.setSize(larghezza, altezza );
frame.setResizable(false);
frame.setVisible(true);
}
...
The Method continue with other code, but it's not important at the moment. So, in Java I create a Jlabel with the image and then I add to the Jframe. What do I have to do in JavaFX in order to show the picture in a stackpane? I tried content.getChildren().addAll(image); where content is a stackpane, but it doesn't work.
Thanks in advance and I apologize for the simplicity of the question.
After converting the BufferedImage to a Javafx Image you have to add a Nodeto the StackPane and the Image isnĀ“t a Node so you can construct an ImageView with the Image.
#FXML StackPane s;
#FXML void initialize(){
BufferedImage b = ImageIO.read(file);
Image i = SwingFXUtils.toFXImage(b, null);
ImageView v = new ImageView(i);
s.getChildren().add(v);
}

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

How to create a button in Libgdx?

I want to create a button that changes when the user hovers it, or clicking it.
I created the following variable
Button buttonPlay = new Button();
I don't know what to do now, how to load the images? How to write text into the button? How to implement the events / effects (hover, click)?
It would be very helpful if someone could write some example code for a button.
A button is simply an actor in libgdx. To render an actor you use a stage that contains all the actors of the screen, renders them and updates them. I assume you want a button with text, so you should use the class TextButton and add it to a stage. A TextButton takes a string to render and a ButtonStyle, in this case a TextButtonStyle, which is basically a class that contains all the information about the button (font, drawable to render while not pressed, drawable to render while pressed etc).
public class ButtonExample extends Game{
Stage stage;
TextButton button;
TextButtonStyle textButtonStyle;
BitmapFont font;
Skin skin;
TextureAtlas buttonAtlas;
#Override
public void create() {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
font = new BitmapFont();
skin = new Skin();
buttonAtlas = new TextureAtlas(Gdx.files.internal("buttons/buttons.pack"));
skin.addRegions(buttonAtlas);
textButtonStyle = new TextButtonStyle();
textButtonStyle.font = font;
textButtonStyle.up = skin.getDrawable("up-button");
textButtonStyle.down = skin.getDrawable("down-button");
textButtonStyle.checked = skin.getDrawable("checked-button");
button = new TextButton("Button1", textButtonStyle);
stage.addActor(button);
}
#Override
public void render() {
super.render();
stage.draw();
}
}
So whats happening here? I am creating a stage, a font and a textureatlas with all the textures for the buttons in "buttons.pack". Then I initialize an empty TextButtonStyle and
and i add the font and the textures for the up, down and checked states. font, up, down and checked are all static variables of type Drawable so you can really pass it any kind of Drawable (texture, 9-patch etc). Then simply add the button to the Stage.
Now in order to do something when the button is actually clicked, you have to add a listener to the button, a ChangeListener.
button.addListener(new ChangeListener() {
#Override
public void changed (ChangeEvent event, Actor actor) {
System.out.println("Button Pressed");
}
});
Of course instead of adding the button directly to the Stage you should add it to a Table and add the Table to the Stage but I didn't want to make this post too confusing. Here is a good tutorial on tables in libgdx.
This is how you do it without adding any skin
TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle();
textButtonStyle.font = yourCustomFont;
textButtonStyle.fontColor = Color.WHITE;
stage.add(new TextButton("Custom Btn ", textButtonStyle));
buttons.pack is the file generated from the libgdx texture packer, texture packer is the tool which can used to generate the texture atlas , That is multiple images you can loaded to the GUI using a single file . it also help to save some memory please refer this link`https://code.google.com/p/libgdx-texturepacker-gui/downloads/list,
https://github.com/libgdx/libgdx/wiki/Texture-packer

Categories