Changing Background Color of Class Attributes using Open API

In class diagram the background color can apply to the entire class, or apply to individual class member. In this article we will demonstrate how to control the background color setting of class attributes in your activate diagram using Visual Paradigm Open API.

Obtain current opening diagram

We first obtain the current opening diagram Visual Paradigm application.

// Obtain active diagram
IDiagramUIModel diagram = ApplicationManager.instance().getDiagramManager().getActiveDiagram();

Walk through the class shapes

Once we obtained the diagram we then retrieve all class shapes into an array. By default the retrieved elements are in IDiagramElement type, we then cast them to IClassUIModel.

// If it is a class diagram then retrieve the class shape form the diagram
if (diagram instanceof IClassDiagramUIModel) {
  IDiagramElement[] diagramElements = diagram.toDiagramElementArray(IShapeTypeConstants.SHAPE_TYPE_CLASS);
  if (diagramElements != null) {
    // Walk through the class shape to obtain its model element,
    // and then retrieve its attributes
    for (IDiagramElement element : diagramElements) {
      if (element instanceof IClassUIModel) {

Changing background color of attributes

Now we obtain the actual model element of the class from IClassUIModel and then retrieve all attributes of the class.

IClass classModel = (IClass) element.getModelElement();

Next we walk through the attributes one by one. If it is in odd number index in the array we then change it background color.

IAttribute[] attributes = classModel.toAttributeArray();
for (int i = 0; i < attributes.length; i++) {
  // Change background color for odd number attributes
  if (i%2 == 0) {
    changeColor((IClassUIModel) element, attributes[i]);
  }
}

In the changeColor method we obtain the ICompartmentColorModel of the attribute then specify its background color.

private void changeColor(IClassUIModel classUIModel, IAttribute attribute) {
  // Obtain the compartment color model of the attribute form class model
  // and change its color
  ICompartmentColorModel colorModel = classUIModel.getCompartmentColorModel(attribute, true);
  Color currentColor = colorModel.getBackground();
  if (currentColor == null) {
    colorModel.setBackground(Color.CYAN);			
  } else{
    if (currentColor.equals(Color.CYAN)) {
      colorModel.setBackground(Color.MAGENTA);
    } else {
      colorModel.setBackground(Color.CYAN);
    }
  }
}

Sample plugin

The sample plugin attached demonstrate how to change the background color of class attributes. After you deploy the plugin into Visual Paradigm you can click the plugin button in application toolbar to change the background color of the attributes.

Trigger sample plugin

Download sample plugin

You can click this link to download the sample plugin.

Related Know-how

Related Link

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply