Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename tab's text on double click in JavaFX 2?

Tags:

tabs

javafx-2

I have a simple code to add tab(s) to a 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);

}

By double left mouse click on a tab I would like to rename (by typing a new text) the selected tab: how can I do this?

like image 633
Alberto acepsut Avatar asked Jun 18 '13 13:06

Alberto acepsut


People also ask

How do you set a hidden label in JavaFX?

Making Labels Invisible You can set the value to this property using the setLabelsVisible() method. To make the labels of the current pie chart invisible you need to invoke this method by passing the boolean value false as a parameter.

What is FX ID in Scene Builder?

The fx:id is the identity associated to component in fxml to build a controller, and the id is used for css.

How do I use tab pane in JavaFX?

Tabs are added to the TabPane by using the getTabs() . Tabs in a TabPane can be positioned at any of the four sides by specifying the Side . A TabPane has two modes floating or recessed. Applying the styleclass STYLE_CLASS_FLOATING will change the TabPane mode to floating.


1 Answers

Here is a solution for my question:

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

}
like image 122
Alberto acepsut Avatar answered Oct 06 '22 23:10

Alberto acepsut