我需要一个Label的可选版本,因此我决定设置和修改TextArea,使其外观和行为类似于常规Label并且可以选择。为使SelectableLabel看起来像常规Label,我需要删除所有填充/边框。我一直在尝试在我的CSS中执行此操作,但我仍然有一些边框/填充,并且不知道如何摆脱它。
这就是它现在的样子
这是我用来设置SelectableLabel样式的CSS的一部分。
#selectable-label {
-fx-background-color: #292929;
-fx-text-fill: white;
}
#selectable-label .content {
-fx-padding: 0;
}
我试图通过搜索互联网来改变我发现的大量其他属性,但到目前为止没有任何效果。
这是示例阶段的来源:
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class ExampleStage extends Stage {
public ExampleStage() {
GridPane gridPane = new GridPane();
gridPane.setPadding(new Insets(20));
gridPane.setHgap(15);
gridPane.setVgap(20);
//First row
Label l1 = new Label("Label 1");
gridPane.add(l1, 0, 0);
GridPane.setHalignment(l1, HPos.RIGHT);
GridPane.setValignment(l1, VPos.TOP);
Label text1 = new Label("This is a regular label");
gridPane.add(text1, 1, 0);
GridPane.setHalignment(text1, HPos.LEFT);
GridPane.setValignment(text1, VPos.TOP);
//Second row
Label l2 = new Label("Label 2");
gridPane.add(l2, 0, 1);
GridPane.setHalignment(l2, HPos.RIGHT);
GridPane.setValignment(l2, VPos.TOP);
SelectableLabel text2 = new SelectableLabel("This is a selectable label");
gridPane.add(text2, 1, 1);
GridPane.setHalignment(text2, HPos.LEFT);
GridPane.setValignment(text2, VPos.TOP);
//Third row
Label l3 = new Label("Label 3");
gridPane.add(l3, 0, 2);
GridPane.setHalignment(l3, HPos.RIGHT);
GridPane.setValignment(l3, VPos.TOP);
Label text3 = new Label("This is a regular label");
gridPane.add(text3, 1, 2);
GridPane.setHalignment(text3, HPos.LEFT);
GridPane.setValignment(text3, VPos.TOP);
Scene scene = new Scene(gridPane);
scene.getStylesheets().add(GUIManager.stylesheet);
this.setScene(scene);
this.setTitle("Example Stage");
this.setResizable(false);
this.show();
}
}
这是SelectableLabel本身的来源:
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
public class SelectableLabel extends TextArea {
public SelectableLabel() {
this("", true);
}
public SelectableLabel(String text) {
this(text, true);
}
public SelectableLabel(String text, boolean selectable) {
super(text);
this.setMouseTransparent(!selectable);
this.setEditable(false);
this.setFocusTraversable(false);
this.setId("selectable-label");
this.setWrapText(true);
sizeToText();
textProperty().addListener(e -> sizeToText());
}
public void setSelectable(boolean selectable) {
setMouseTransparent(!selectable);
}
private void sizeToText() {
Text t = new Text(getText());
t.setFont(this.getFont());
StackPane pane = new StackPane(t);
pane.layout();
double width = t.getLayoutBounds().getWidth();
double height = t.getLayoutBounds().getHeight();
this.setMaxSize(width, height);
}
}