Copiable Label/TextField/LabeledText in JavaFX

后端 未结 2 1840
悲&欢浪女
悲&欢浪女 2020-11-29 09:46

I just want to create copiable label in JavaFX. I have tried to create TextField that have no background, have no focus border and default background color, but I have no su

2条回答
  •  醉话见心
    2020-11-29 10:13

    This is the solution I used, where there is a small button besides the label to be able to copy the text:

    import javafx.geometry.Insets;
    import javafx.scene.Node;
    import javafx.scene.control.Button;
    import javafx.scene.control.ContentDisplay;
    import javafx.scene.control.Label;
    import org.controlsfx.glyphfont.FontAwesome;
    import org.controlsfx.glyphfont.Glyph;
    
    import java.util.Locale;
    
    public class CopiableLabel extends Label
    {
        public CopiableLabel()
        {
            addCopyButton();
        }
    
        public CopiableLabel(String text)
        {
            super(text);
            addCopyButton();
        }
    
        public CopiableLabel(String text, Node graphic)
        {
            super(text, graphic);
        }
    
        private void addCopyButton()
        {
            Button button = new Button();
            button.visibleProperty().bind(textProperty().isEmpty().not());
            button.managedProperty().bind(textProperty().isEmpty().not());
            button.setFocusTraversable(false);
            button.setPadding(new Insets(0.0, 4.0, 0.0, 4.0));
            button.setOnAction(actionEvent -> AppUtils.copyToClipboard(getText()));
            Glyph clipboardIcon = AppUtils.createFontAwesomeIcon(FontAwesome.Glyph.CLIPBOARD);
            clipboardIcon.setFontSize(8.0);
            button.setGraphic(clipboardIcon);
            setGraphic(button);
            setContentDisplay(ContentDisplay.RIGHT);
        }
    }
    

提交回复
热议问题