【问题标题】:Copiable Label/TextField/LabeledText in JavaFXJavaFX 中的可复制标签/文本字段/标签文本
【发布时间】:2014-04-27 08:42:30
【问题描述】:

我只想在 JavaFX 中创建可复制的标签。 我尝试创建没有背景、没有焦点边框和默认背景颜色的 TextField,但没有成功。 我发现了很多关于如何从控制中移除焦点背景的问题,但所有这些看起来都像是“黑客”。

是否有实现可复制文本的标准解决方案?

【问题讨论】:

  • 没有标准的方法,但有 a bug filed 来改变它。

标签: javafx javafx-2 javafx-8


【解决方案1】:

你可以用css创建一个没有边框和背景颜色的TextField:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class CopyableLabel extends Application {

    @Override
    public void start(Stage primaryStage) {
        TextField copyable = new TextField("Copy this");
        copyable.setEditable(false);
        copyable.getStyleClass().add("copyable-label");

        TextField tf2 = new TextField();
        VBox root = new VBox();
        root.getChildren().addAll(copyable, tf2);
        Scene scene = new Scene(root, 250, 150);
        scene.getStylesheets().add(getClass().getResource("copyable-text.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

和

可复制文本.css:

.copyable-label, .copyable-label:focused {
    -fx-background-color: transparent ;
    -fx-background-insets: 0px ;
}

【讨论】:

  • 我可以在标签或窗格上做同样的事情。有没有办法做到这一点
  • 我们如何摆脱上下文菜单?
  • @MouseEvent,这里是how to get rid of the context menu
【解决方案2】:

这是我使用的解决方案,在标签旁边有一个小按钮可以复制文本:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多