2017-05-25 50 views
2

有沒有辦法在JavaFx8中選擇一個標籤文本?我知道,還有其他簡單的解決方法就像使用TextField一樣。但是我的標籤需要多行文字和TextField沒有提供的包裝功能。如果我使用TextArea,問題是我無法根據文本的大小像標籤一樣縮小TextArea。所以我不能使用他們中的任何一個。如何使Javafx標籤可選

而且我使用的標籤文本是象下面這樣:

<VBox> 
    <Label wrapText="true" 
      VBox.vgrow="ALWAYS" 
      maxHeight="Infinity" minHeight="-Infinity" 
      text="Some Random Subject Line With Very Large Text To Test The Wrap Text, Lorem Ipsum Dolor"/>      
</VBox> 

根據垂直框寬度,標籤的高度調整大小以完全適合文本。我無法使用TextArea或TextField來模擬這種行爲。但我需要能夠從標籤中選擇文本。有任何想法嗎?

+0

我不認爲這是可能的,或者至少那是什麼[這裏](https://community.oracle.com/thread/2319231)甲骨文suggests.Looks喜歡它的線程的請求功能在未來的版本中實施。 –

+0

那麼任何人都可以創建任何開源自定義控件? –

+0

試試這個:https://stackoverflow.com/questions/22534067/copiable-label-textfield-labeledtext-in-javafx – 2017-05-25 07:30:05

回答

4

這是一個解決方法,直到有人發佈更好的東西。

如果您雙擊標籤,它將更改爲TextArea。然後您可以複製文本。一旦按下TextArea上的輸入,它就會變回標籤。

import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.Label; 
import javafx.scene.control.TextArea; 
import javafx.scene.input.MouseButton; 
import javafx.scene.input.MouseEvent; 
import javafx.scene.layout.Priority; 
import javafx.scene.layout.StackPane; 
import javafx.scene.layout.VBox; 
import javafx.stage.Stage; 

/** 
* 
* @author blj0011 
*/ 
public class JavaFXApplication110 extends Application 
{ 

    @Override 
    public void start(Stage primaryStage) 
    { 
     VBox root = new VBox(); 

     StackPane stackpane = new StackPane();   

     Label label = new Label("Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world"); 
     VBox.setVgrow(label, Priority.ALWAYS); 
     label.wrapTextProperty().set(true); 

     label.setOnMouseClicked(new EventHandler<MouseEvent>() { 
      @Override 
      public void handle(MouseEvent mouseEvent) { 
       if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ 
        if(mouseEvent.getClickCount() == 2){ 
         label.setVisible(false); 
         TextArea textarea = new TextArea(label.getText()); 
         textarea.setPrefHeight(label.getHeight() + 10); 
         stackpane.getChildren().add(textarea); 

         textarea.setOnKeyPressed(event ->{ 
          System.out.println(event.getCode()); 
          if(event.getCode().toString().equals("ENTER")) 
          { 
           stackpane.getChildren().remove(textarea); 
           label.setVisible(true);        
          } 
         }); 
        } 
       } 
      } 
     }); 

     stackpane.getChildren().add(label); 

     root.getChildren().add(stackpane); 

     Scene scene = new Scene(root, 300, 250); 

     primaryStage.setTitle("Hello World!"); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) 
    { 
     launch(args); 
    } 

} 
+0

這是一個聰明的解決方法,我喜歡它。 –