package tests; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author sjiang */ public class MyTabPane2 extends Application { public static boolean toAdd = false; public static Tab toAddTab; public static void main(String[] args) throws Exception { Application.launch(args); } @Override public void start(Stage stage) throws Exception { TabPane tp1 = create("1"); Scene scene = new Scene(tp1); stage.setScene(scene); stage.setVisible(true); } public TabPane create(String id) { final TabPane tabPane = new TabPane(); Rectangle rec1 = new Rectangle(50, 50); rec1.setFill(Color.RED); Tab tab1 = new Tab(); tab1.setContent(rec1); tab1.setText("1"); Rectangle rec2 = new Rectangle(50, 50); rec2.setFill(Color.BLACK); Tab tab2 = new Tab(); tab2.setContent(rec2); tab2.setText("2"); Rectangle rec3 = new Rectangle(50, 50); rec3.setFill(Color.BLUE); Tab tab3 = new Tab(); tab3.setContent(rec3); tab3.setText("3"); toAddTab = tab1; tabPane.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent me) { if (toAdd) { tabPane.getTabs().add(toAddTab); toAdd = false; System.out.println("---jsl clicked to add a tab. Size=" + tabPane.getTabs().size()); } else { for (Tab tab : tabPane.getTabs()) { if (tab.isSelected()) { toAddTab = tab; break; } } tabPane.getTabs().remove(toAddTab); toAdd = true; System.out.println("---jsl clicked to remove a tab. Size=" + tabPane.getTabs().size()); } checkSelection(tabPane); } }); tabPane.getTabs().addAll(tab1, tab2, tab3); tabPane.resize(200, 200); return tabPane; } private void checkSelection(TabPane tabPane) { int selected = 0; for (Tab t : tabPane.getTabs()) { if (t.isSelected()) { selected++; } } if (selected != 1) { throw new RuntimeException("Can select more than one tab ?"); } } }