如何在JavaFX 2中双击重命名选项卡的文本?

时间:2013-06-18 13:34:29

标签: tabs javafx-2

我有一个简单的代码,可以将标签添加到tabPane

@FXML
private void addNewWorkspaceTab(ActionEvent event) {

    Tab workspaceTab = new Tab();
    workspaceTab.setText("New Workspace");
    tabpaneWorkspace.getTabs().addAll(workspaceTab);
    tabpaneWorkspace.setTabClosingPolicy(TabPane.TabClosingPolicy.SELECTED_TAB);

}

通过双击鼠标左键单击选项卡,我想重命名(通过键入新文本)所选标签:我该怎么做?

1 个答案:

答案 0 :(得分:2)

以下是我的问题的解决方案:

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;

/**
*
* @author utente
*/
public class TabSetText {

public Tab createEditableTab(String text) {  
final Label label = new Label(text);  
final Tab tab = new Tab();  
tab.setGraphic(label);  
final TextField textField = new TextField();  
label.setOnMouseClicked(new EventHandler<MouseEvent>() {  
  @Override  
  public void handle(MouseEvent event) {  
    if (event.getClickCount()==2) {  
      textField.setText(label.getText());  
      tab.setGraphic(textField);  
      textField.selectAll();  
      textField.requestFocus();  
    }  
  }  
}); 


textField.setOnAction(new EventHandler<ActionEvent>() {  
  @Override  
  public void handle(ActionEvent event) {  
    label.setText(textField.getText());  
    tab.setGraphic(label);  
  }  
});


textField.focusedProperty().addListener(new ChangeListener<Boolean>() {  
  @Override  
  public void changed(ObservableValue<? extends Boolean> observable,  
      Boolean oldValue, Boolean newValue) {  
    if (! newValue) {  
      label.setText(textField.getText());  
      tab.setGraphic(label);            
    }  
  }  
});  
return tab ;  
}  

}