Thursday, July 25, 2013

PlayN / tripleplay - Simple Progressbar

Since there is no default progressbar widget in the tripleplay gui framework, I've build my  own one. Feel free to use, improvements are appreciated. I use it for the visualization of creature's lifeenergy in my game. 

 
package de.creaturewars.client.gui;

import tripleplay.ui.Background;
import tripleplay.ui.SizableGroup;
import tripleplay.ui.Style;
import tripleplay.ui.layout.AxisLayout;

/**
 * 
 * @author Paul Weibert
 * 
 */
public class ProgressBar extends SizableGroup {

 private final int BAR_COLOR = 0xff379aff;
 private final int EMPTY_COLOR = 0xff000000;
 private float maxValue = 100;
 private float value = 0;
 private SizableGroup bar;
 private float barHeight = 10;

 public ProgressBar(float width, float height) {
  super(AxisLayout.horizontal());
  this.preferredSize.update(width, height);
  this.addStyles(Style.HALIGN.left);
  this.bar = new SizableGroup(AxisLayout.horizontal());
  this.addStyles(Style.BACKGROUND.is(Background.solid(EMPTY_COLOR)));
  this.bar.setStyles(Style.BACKGROUND.is(Background.solid(BAR_COLOR)));
  this.bar.addStyles(Style.HALIGN.left);

  add(bar);
 }

 public void setValue(float value) {
  this.value = value;
  dataChanged();
 }

 public void setMaxValue(float maxValue) {
  this.maxValue = maxValue;
  dataChanged();
 }

 private void dataChanged() {
  float w = this.preferredSize.get().width();
  float qoutient = w / maxValue;
  float barWidth = qoutient * value;
  final float maxWidth = this.preferredSize.get().width();
  
  
  if(barWidth > maxWidth){
   barWidth = maxWidth;
  }
  
  bar.preferredSize.update(barWidth, barHeight);
 }

 public void setBarHeight(float barHeight) {
  this.barHeight = barHeight;
 }

}