JavaFX - create custom button with image

前端 未结 3 818
粉色の甜心
粉色の甜心 2020-11-30 04:15

I would like to create a custom button, that has two states pressed or not, like a toggle button. I have got two images to do this (pressed and not pressed), so how can i c

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 04:52

    You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

    public class ImageButton extends Parent {
    
        private static final Image NORMAL_IMAGE = ...;
        private static final Image PRESSED_IMAGE = ...;
    
        private final ImageView iv;
    
        public ImageButton() {
            this.iv = new ImageView(NORMAL_IMAGE);
            this.getChildren().add(this.iv);
    
            this.iv.setOnMousePressed(new EventHandler() {
    
                public void handle(MouseEvent evt) {
                    iv.setImage(PRESSED_IMAGE);
                }
    
            });
    
            // TODO other event handlers like mouse up
    
        } 
    
    }
    

提交回复
热议问题