Skip to content
Advertisement

Place icon into top right of tabpane javaFX

I am using JavaFX 8 and have a tab pane as this:

image

I was wondering if there was any way to place an icon into the top right of the tab pane such as in this

image

My goal is to have a colored indicator in the top right of the tab pane that I can toggle between green

green

and red as needed. Is there any way to add a colored circle or something similar into the top right of a tab pane?

Advertisement

Answer

You can use the following structure of nodes to achieve what you want.

-AnchorPane
    -TabPane
    -StackPane

Idea

Tab pane will completely occupy the anchor pane. Stack pane will be anchored to the top right corner of the anchor pane and it be positioned on top of tab pane. The size of the stack pane will be adjusted so it appears as an icon on the top right corner. Finally, circle will be added to the stack pane.


FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane prefHeight="400.0" prefWidth="600.0" 
            xmlns="http://javafx.com/javafx/11.0.2" 
            xmlns:fx="http://javafx.com/fxml/1"
            fx:controller="com.example.tabpane.TabPaneController">

    <TabPane prefHeight="200.0" prefWidth="200.0" tabClosingPolicy="UNAVAILABLE" 
             AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" 
             AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">

             <!--tabs here-->

    </TabPane>

    <StackPane fx:id="icon" prefHeight="30.0" prefWidth="30.0" 
               AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"/>
</AnchorPane>

Controller

package com.example.tabpane;

import javafx.fxml.FXML;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

public class TabPaneController
{
    @FXML
    private StackPane icon;

    @FXML
    public void initialize()
    {
        Circle circle = new Circle(7, Color.RED);
        icon.getChildren().add(circle);
    }
}

Output

enter image description here


This even works when resizing your application till you make the application window too small. If this is the best way to achieve what you want, that I do not know. If you face any problems, do comment.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement