Java Code Examples for org.apache.commons.lang3.text.WordUtils

The following examples show how to use org.apache.commons.lang3.text.WordUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: arcusandroid   Source File: StringUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static SpannableString getDateStringDayAndTime (Date dateValue) {
    DateFormat timeFormat = new SimpleDateFormat("  h:mm", Locale.US);
    DateFormat ampmFormat = new SimpleDateFormat(" a", Locale.US);
    DateFormat dateFormat = new SimpleDateFormat("EEE", Locale.US);
    DateFormat dateFormatWithTime = new SimpleDateFormat("    h:mm a", Locale.US);

    if (dateValue == null) {
        return new SpannableString(ArcusApplication.getContext().getString(R.string.unknown_time_value));
    }

    // Date is today; just show the time
    else if (StringUtils.isDateToday(dateValue)) {
        return StringUtils.getSuperscriptSpan(ArcusApplication.getContext().getString(R.string.today), dateFormatWithTime.format(dateValue));
    }

    // Date is yesterday; show "YESTERDAY"
    else if (StringUtils.isDateYesterday(dateValue)) {
        return new SpannableString(ArcusApplication.getContext().getString(R.string.yesterday));
    }

    // Date is in the past; show date
    else {
        return StringUtils.getSuperscriptSpan(WordUtils.capitalize(dateFormat.format(dateValue)), dateFormatWithTime.format(dateValue));
    }
}
 
Example 2
Source Project: CQL   Source File: CodeEditor.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
protected static String truncate(String w) {
		boolean truncated = false;
		if (w.length() > 2048) {
			w = w.substring(0, 2048);
			truncated = true;
		}
		String lines[] = w.split("\\r?\\n");
		StringBuffer sb = new StringBuffer();
		int i = 0;
		for (String line : lines) {
			if (i++ == 40) {
				truncated = true;
				break;
			}
			sb.append(WordUtils.wrap(line, 40));			
		}
		if (truncated) {
			sb.append("\n\nThis error message was truncated.");
		}
		return sb.toString();
//		
//		List<String> s = w.lines().map(x -> x.substring(0, Integer.min(80, x.length()))).collect(Collectors.toList());
//		return Util.sep(s.subList(0, Integer.min(s.size(), 80)), "\n");
	}
 
Example 3
Source Project: astor   Source File: StringUtilsTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSwapCase_String() {
    assertEquals(null, StringUtils.swapCase(null));
    assertEquals("", StringUtils.swapCase(""));
    assertEquals("  ", StringUtils.swapCase("  "));
    
    assertEquals("i", WordUtils.swapCase("I") );
    assertEquals("I", WordUtils.swapCase("i") );
    assertEquals("I AM HERE 123", StringUtils.swapCase("i am here 123") );
    assertEquals("i aM hERE 123", StringUtils.swapCase("I Am Here 123") );
    assertEquals("I AM here 123", StringUtils.swapCase("i am HERE 123") );
    assertEquals("i am here 123", StringUtils.swapCase("I AM HERE 123") );
    
    String test = "This String contains a TitleCase character: \u01C8";
    String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9";
    assertEquals(expect, WordUtils.swapCase(test));
}
 
Example 4
Source Project: The-5zig-Mod   Source File: HypixelPaintballListener.java    License: MIT License 6 votes vote down vote up
@Override
public void onMatch(ServerHypixel.Paintball gameMode, String key, IPatternResult match) {
	if (gameMode.getState() == GameState.LOBBY) {
		if (key.equals("starting")) {
			gameMode.setTime(System.currentTimeMillis() + Integer.parseInt(match.get(0)) * 1000);
		}
	}
	if (gameMode.getState() == GameState.GAME) {
		if (key.equals("paintball.kill")) {
			gameMode.setKills(gameMode.getKills() + 1);
		}
		if (key.equals("paintball.death")) {
			gameMode.setDeaths(gameMode.getDeaths() + 1);
		}
	}
	if (key.equals("paintball.team")) {
		gameMode.setTeam(WordUtils.capitalize(match.get(0).toLowerCase(Locale.ROOT)));
	}
}
 
Example 5
Source Project: Shuffle-Move   Source File: TypeChooser.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void setSelectedType(PkmType type) {
   String toSelect = null;
   if (type != null) {
      if (shouldRebuild) {
         refill();
      }
      toSelect = WordUtils.capitalizeFully(type.toString());
      DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) getModel();
      if (model.getIndexOf(toSelect) == -1) {
         shouldRebuild = true;
         insertItemAt(toSelect, 0);
      } else {
         shouldRebuild = false;
      }
   }
   setSelectedItem(toSelect);
}
 
Example 6
Source Project: ExtraCells1   Source File: WidgetFluidRequest.java    License: MIT License 6 votes vote down vote up
@Override
public void drawWidget(int posX, int posY)
{
	Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture);
	GL11.glPushMatrix();
	GL11.glDisable(GL11.GL_LIGHTING);
	GL11.glColor3f(1.0F, 1.0F, 1.0F);
	if (fluid != null && fluid.getIcon() != null)
	{
		drawTexturedModelRectFromIcon(posX + 1, posY + 1, fluid.getIcon(), sizeX - 2, sizeY - 2);
		GL11.glScalef(0.5F, 0.5F, 0.5F);
		String str = StatCollector.translateToLocal("AppEng.Terminal.Craft");
		str = WordUtils.capitalize(str.toLowerCase());
		Minecraft.getMinecraft().fontRenderer.drawString(EnumChatFormatting.WHITE + str, 52 + posX - str.length(), posY + 24, 0);
	}
	GL11.glEnable(GL11.GL_LIGHTING);
	GL11.glPopMatrix();
}
 
Example 7
Source Project: xibalba   Source File: CharacterScreen.java    License: MIT License 6 votes vote down vote up
private void updateSkillsGroup() {
  skillsGroup.clear();

  skillsGroup.addActor(new Label("Skills", Main.skin));
  skillsGroup.addActor(new Label("", Main.skin));

  for (Map.Entry<String, Integer> entry : skills.levels.entrySet()) {
    String skill = entry.getKey();
    Integer level = entry.getValue();

    if (level > 0) {
      String name = WordUtils.capitalize(skill);

      skillsGroup.addActor(new Label(
          "[LIGHT_GRAY]" + name + " [WHITE]" + level + "[DARK_GRAY]d", Main.skin
      ));
    }
  }
}
 
Example 8
Source Project: xibalba   Source File: CharacterScreen.java    License: MIT License 6 votes vote down vote up
private void updateTraitsGroup() {
  traitsGroup.clear();

  traitsGroup.addActor(new Label("Traits", Main.skin));
  traitsGroup.addActor(new Label("", Main.skin));

  for (TraitData traitData : this.traits) {
    if (WorldManager.entityHelpers.hasTrait(WorldManager.player, traitData.name)) {
      traitsGroup.addActor(
          new Label(
              "[GREEN]" + traitData.name + "\n[DARK_GRAY]" + WordUtils.wrap(
                  traitData.description, 50
              ), Main.skin
          )
      );
    }
  }
}
 
Example 9
Source Project: xibalba   Source File: CharacterScreen.java    License: MIT License 6 votes vote down vote up
private void updateDefectsGroup() {
  defectsGroup.clear();

  defectsGroup.addActor(new Label("Defects", Main.skin));
  defectsGroup.addActor(new Label("", Main.skin));

  for (DefectData defectData : this.defects) {
    if (WorldManager.entityHelpers.hasDefect(WorldManager.player, defectData.name)) {
      defectsGroup.addActor(
          new Label(
              "[RED]" + defectData.name + "\n[DARK_GRAY]" + WordUtils.wrap(
                  defectData.description, 50
              ), Main.skin
          )
      );
    }
  }
}
 
Example 10
Source Project: Entitas-Java   Source File: ComponentLookupGenerator.java    License: MIT License 6 votes vote down vote up
private JavaClassSource generateIndicesLookup(String contextName, List<ComponentData> dataList) {
    String pkgDestiny = targetPackageConfig.getTargetPackage();

    JavaClassSource codeGen = Roaster.parse(JavaClassSource.class, String.format("public class %1$s {}",
            WordUtils.capitalize(contextName) + DEFAULT_COMPONENT_LOOKUP_TAG));
    if (dataList.size() > 0 && !pkgDestiny.endsWith(dataList.get(0).getSubDir()) ) {
       // pkgDestiny += "." + dataList.get(0).getSubDir();

    }
    codeGen.setPackage(pkgDestiny);

    addIndices(dataList, codeGen);
    addComponentNames(dataList, codeGen);
    addComponentTypes(dataList, codeGen);
    System.out.println(codeGen);

    return codeGen;
}
 
Example 11
Source Project: astor   Source File: StringUtilsTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSwapCase_String() {
    assertEquals(null, StringUtils.swapCase(null));
    assertEquals("", StringUtils.swapCase(""));
    assertEquals("  ", StringUtils.swapCase("  "));
    
    assertEquals("i", WordUtils.swapCase("I") );
    assertEquals("I", WordUtils.swapCase("i") );
    assertEquals("I AM HERE 123", StringUtils.swapCase("i am here 123") );
    assertEquals("i aM hERE 123", StringUtils.swapCase("I Am Here 123") );
    assertEquals("I AM here 123", StringUtils.swapCase("i am HERE 123") );
    assertEquals("i am here 123", StringUtils.swapCase("I AM HERE 123") );
    
    String test = "This String contains a TitleCase character: \u01C8";
    String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9";
    assertEquals(expect, WordUtils.swapCase(test));
}
 
Example 12
Source Project: camunda-bpm-swagger   Source File: ApiOperationStep.java    License: Apache License 2.0 6 votes vote down vote up
public void annotate(final MethodStep methodStep, final Method m) {

    // resources are not annotated at all, because the resource itself will contain a method
    // that will get into the public API. It is a method with GET annotation and empty path.
    if (!TypeHelper.isResource(methodStep.getReturnType())) {
      final String description = restOperation != null && restOperation.getDescription() != null ? restOperation.getDescription() : WordUtils.capitalize(StringHelper.splitCamelCase(m.getName()));

      getMethod().annotate(ApiOperation.class) //
        .param("value", StringHelper.firstSentence(description))
        .param("notes", description)
      ;

      if (restOperation != null && restOperation.getExternalDocUrl() != null) {
        getMethod().annotate(ExternalDocs.class)
          .param("value", "Reference Guide")
          .param("url", restOperation.getExternalDocUrl())
        ;
      }
    }
  }
 
Example 13
Source Project: bunk   Source File: ResponseParser.java    License: MIT License 6 votes vote down vote up
private Student processLogin(String loginJson) {
    JsonObject login;
    try {
        login = this.jsonParser.parse(loginJson).getAsJsonObject();
    } catch (Exception e) {
        throw new InvalidResponseException();
    }

    if (!login.has("status") || !login.has("name")) {
        throw new InvalidResponseException();
    }

    if (!login.get("status").getAsString().equals("success")) {
        throw new InvalidCredentialsException();
    }

    Student student = new Student();
    student.name = WordUtils.capitalizeFully(login.get("name").getAsString());

    return student;
}
 
Example 14
Source Project: PneumaticCraft   Source File: ProgWidget.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void renderExtraInfo(){
    if(getExtraStringInfo() != null) {
        GL11.glPushMatrix();
        GL11.glScaled(0.5, 0.5, 0.5);
        FontRenderer fr = Minecraft.getMinecraft().fontRenderer;
        String[] splittedInfo = WordUtils.wrap(getExtraStringInfo(), 40).split(System.getProperty("line.separator"));
        for(int i = 0; i < splittedInfo.length; i++) {
            int stringLength = fr.getStringWidth(splittedInfo[i]);
            int startX = getWidth() / 2 - stringLength / 4;
            int startY = getHeight() / 2 - (fr.FONT_HEIGHT + 1) * (splittedInfo.length - 1) / 4 + (fr.FONT_HEIGHT + 1) * i / 2 - fr.FONT_HEIGHT / 4;
            Gui.drawRect(startX * 2 - 1, startY * 2 - 1, startX * 2 + stringLength + 1, startY * 2 + fr.FONT_HEIGHT + 1, 0xFFFFFFFF);
            fr.drawString(splittedInfo[i], startX * 2, startY * 2, 0xFF000000);
        }
        GL11.glPopMatrix();
        GL11.glColor4d(1, 1, 1, 1);
    }
}
 
Example 15
Source Project: rug-cli   Source File: CommandHelpFormatter.java    License: GNU General Public License v3.0 6 votes vote down vote up
public String printCommandHelp(CommandInfo description) {
    StringBuilder sb = new StringBuilder();

    sb.append(String.format("Usage: %s%s\n", Style.bold(Constants.command()),
            Style.bold(description.usage())));
    if (!description.aliases().isEmpty()) {
        sb.append(String.format("%s: %s\n",
                com.atomist.rug.cli.utils.StringUtils.puralize("Alias", "Aliases",
                        description.aliases()),
                Style.bold(
                        StringUtils.collectionToDelimitedString(description.aliases(), ", "))));
    }
    sb.append(String.format("%s.\n", description.description()));

    printOptions(description.globalOptions(), sb, Style.bold("Options"));
    printOptions(description.options(), sb, Style.bold("Command Options"));

    sb.append("\n");
    sb.append(WordUtils.wrap(description.detail(), WRAP));
    sb.append(WordUtils.wrap(HELP_FOOTER, WRAP));

    return sb.toString();

}
 
Example 16
Source Project: Signals   Source File: SignalStatusRenderer.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void render(TileEntitySignalBase te, double x, double y,
		double z, float partialTicks, int destroyStage, float alpha) {
	String message = te.getMessage();
	if(message.equals("")) return;
	
	GlStateManager.pushMatrix();
	GlStateManager.translate((float)x + 0.5F, (float)y + 1.0, (float)z + 0.5F);
	GlStateManager.rotate(180 + Minecraft.getMinecraft().getRenderManager().playerViewY, 0.0F, -1.0F, 0.0F);
	GlStateManager.rotate(Minecraft.getMinecraft().getRenderManager().playerViewX, -1.0F, 0.0F,0.0F);
	double scale = 1/32D;
	GlStateManager.scale(scale, -scale, scale);
	
	String[] splitted = WordUtils.wrap(message, 40).split("\r\n");
	FontRenderer f = Minecraft.getMinecraft().fontRenderer;
	for(int i = 0; i < splitted.length; i++){
		String line = splitted[i];
		f.drawString(line, -f.getStringWidth(line) / 2, (i - splitted.length + 1) * (f.FONT_HEIGHT + 1), 0xFFFFFFFF);
	}
	
	GlStateManager.popMatrix();
}
 
Example 17
Source Project: cloudbreak   Source File: AwsResourceNameService.java    License: Apache License 2.0 6 votes vote down vote up
private String instanceName(Object[] parts) {
    checkArgs(INSTANCE_NAME_PART_COUNT, parts);
    String name;
    String stackName = String.valueOf(parts[0]);
    String instanceGroupName = WordUtils.initials(String.valueOf(parts[1]).replaceAll("_", " "));
    String privateId = String.valueOf(parts[2]);

    name = normalize(stackName);
    name = adjustPartLength(name);
    name = appendPart(name, normalize(instanceGroupName));
    name = appendPart(name, privateId);
    name = appendHash(name, new Date());
    name = adjustBaseLength(name, maxResourceNameLength);

    return name;
}
 
Example 18
Source Project: arcusandroid   Source File: DateUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String formatSunriseSunset(@NonNull TimeOfDay timeOfDay) {
    String riseSet = WordUtils.capitalize(timeOfDay.getSunriseSunset().name().toLowerCase());
    int offset = timeOfDay.getOffset();
    if (offset == 0) {
        return String.format("At %s", riseSet);
    }
    else {
        boolean before = offset < 0;
        return String.format("%s Min %s %s", Math.abs(offset), before ? "Before" : "After", riseSet);
    }
}
 
Example 19
Source Project: arcusandroid   Source File: TimeWindowModel.java    License: Apache License 2.0 5 votes vote down vote up
public Map<String, Object> toMap() {
    return ImmutableMap.<String, Object>of(
          CareKeys.ATTR_TIMEWINDOW_DAY.attrName(), WordUtils.capitalize(day.name().toLowerCase()),
          CareKeys.ATTR_TIMEWINDOW_DURATIONSECS.attrName(), durationSecs,
          CareKeys.ATTR_TIMEWINDOW_STARTTIME.attrName(), startTime
    );
}
 
Example 20
Source Project: arcusandroid   Source File: RuleTemplateView.java    License: Apache License 2.0 5 votes vote down vote up
public void setRuleTemplate (@NonNull List<TemplateTextField> fields, OnTemplateFieldClickListener listener) {

        this.setText("");

        for (TemplateTextField thisField : fields) {

            // Capitalize proper nouns; lowercase all other editable fields.
            String displayText = thisField.getText();
            if (thisField.isEditable()) {
                displayText = thisField.isProperName() ? WordUtils.capitalizeFully(displayText) : displayText.toLowerCase();
            }

            SpannableStringBuilder span = SpannableStringBuilder.valueOf(displayText);

            if (thisField.isEditable()) {
                span.setSpan(new EditableSpan(thisField, listener), 0, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            int textColor = thisField.isEditable() ? Color.BLACK : Color.GRAY;
            span.setSpan(new ForegroundColorSpan(textColor), 0, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            this.append(span);
        }

        this.setHighlightColor(Color.TRANSPARENT);

        if (enabled) {
            this.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }
 
Example 21
Source Project: Entitas-Java   Source File: EntitasGenerator.java    License: MIT License 5 votes vote down vote up
private void createMethodConstructor(JavaClassSource javaClass, Set<String> contextNames) {
    String setAllContexts = contextNames.stream().reduce("\n", (acc, contextName) ->
            acc + "    " + contextName.toLowerCase() + " = create" + WordUtils.capitalize(contextName) + "Context();\n "
    );


    javaClass.addMethod()
            .setConstructor(true)
            .setPublic()
            .setBody(setAllContexts);
}
 
Example 22
Source Project: Flink-CEPplus   Source File: JaccardIndex.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getLongDescription() {
	return WordUtils.wrap(new StrBuilder()
		.appendln("Jaccard Index measures the similarity between vertex neighborhoods and " +
			"is computed as the number of shared neighbors divided by the number of " +
			"distinct neighbors. Scores range from 0.0 (no shared neighbors) to 1.0 (all " +
			"neighbors are shared).")
		.appendNewLine()
		.append("The result contains two vertex IDs, the number of shared neighbors, and " +
			"the number of distinct neighbors.")
		.toString(), 80);
}
 
Example 23
Source Project: Flink-CEPplus   Source File: TriangleListing.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getLongDescription() {
	return WordUtils.wrap(new StrBuilder()
		.appendln("List all triangles graph.")
		.appendNewLine()
		.append("The algorithm result contains three vertex IDs. For the directed algorithm " +
			"the result contains an additional bitmask indicating the presence of the six " +
			"potential connecting edges.")
		.toString(), 80);
}
 
Example 24
Source Project: Flink-CEPplus   Source File: AdamicAdar.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getLongDescription() {
	return WordUtils.wrap(new StrBuilder()
		.appendln("Adamic-Adar measures the similarity between vertex neighborhoods and is " +
			"computed as the sum of the inverse logarithm of centerpoint degree over shared " +
			"neighbors.")
		.appendNewLine()
		.append("The algorithm result contains two vertex IDs and the similarity score.")
		.toString(), 80);
}
 
Example 25
Source Project: find   Source File: FilterITCase.java    License: MIT License 5 votes vote down vote up
@Test
public void testFilterPanelAndModalLinked() {
    searchAndWait("cats");
    final FilterPanel filterPanel = filters();

    final ParametricFieldContainer container = filterPanel.parametricField(1);
    final String filterCategory = container.filterCategoryName();

    final FindParametricFilter checkbox = filterPanel.checkboxForParametricValue(1, 1);
    final List<String> selectedFilter = Collections.singletonList(checkbox.getName());
    checkbox.check();

    findPage.waitForParametricValuesToLoad();

    final ParametricFieldContainer refreshedContainer = filterPanel.parametricContainer(WordUtils.capitalize(filterCategory.toLowerCase()));
    refreshedContainer.expand();
    refreshedContainer.seeAll();

    final ParametricFilterModal filterModal = ParametricFilterModal.getParametricModal(getDriver());
    filterModal.waitForLoad();

    verifyThat("Modal not loading forever", !filterModal.isCurrentTabLoading());
    verifyThat("Correct tab is active", filterModal.activeTabName(), equalToIgnoringCase(filterCategory));
    verifyThat("Same fields selected in modal as panel", filterModal.checkedFiltersAllPanes(), is(selectedFilter));

    final String filterType = filterModal.activeTabName();
    final String checkedFilterName = filterModal.checkCheckBoxInActivePane(0);
    filterModal.apply();

    final FindParametricFilter panelBox = filterPanel.checkboxForParametricValue(filterType, checkedFilterName);
    verifyThat("Filter: " + checkedFilterName + " is now checked on panel", panelBox.isChecked());
}
 
Example 26
Source Project: nifi   Source File: ExtractHL7Attributes.java    License: Apache License 2.0 5 votes vote down vote up
private static Map<String, Type> getAllFields(final String segmentKey, final Segment segment, final boolean useNames) throws HL7Exception {
    final Map<String, Type> fields = new TreeMap<>();
    final String[] segmentNames = segment.getNames();
    for (int i = 1; i <= segment.numFields(); i++) {
        final Type field = segment.getField(i, 0);
        if (!isEmpty(field)) {
            final String fieldName;
            //Some user defined segments (e.g. Z segments) will not have corresponding names returned
            //from segment.getNames() above. If we encounter one of these, do the next best thing
            //and return what we otherwise would if we were not in useNames mode.
            String segmentName = segmentNames[i-1];
            if (useNames && StringUtils.isNotBlank(segmentName)) {
                fieldName = WordUtils.capitalize(segmentName).replaceAll("\\W+", "");
            } else {
                fieldName = String.valueOf(i);
            }

            final String fieldKey = new StringBuilder()
                .append(segmentKey)
                .append(".")
                .append(fieldName)
                .toString();

            fields.put(fieldKey, field);
        }
    }
    return fields;
}
 
Example 27
Source Project: flink   Source File: HITS.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getLongDescription() {
	return WordUtils.wrap(new StrBuilder()
		.appendln("Hyperlink-Induced Topic Search computes two interdependent scores for " +
			"each vertex in a directed graph. A good \"hub\" links to good \"authorities\" " +
			"and good \"authorities\" are linked to from good \"hubs\".")
		.appendNewLine()
		.append("The result contains the vertex ID, hub score, and authority score.")
		.toString(), 80);
}
 
Example 28
@Test
public void capitalize_each_word_in_sentence_apache_commons () {
	
	String prideAndPrejudiceSentence = "It is a truth universally acknowledged, "
			+ "that a single man in possession of a good fortune, must be in want of a wife.";
	
	String eachWordCapitalized = WordUtils.capitalizeFully(prideAndPrejudiceSentence);
	
	assertEquals("It Is A Truth Universally Acknowledged, That A Single "
			+ "Man In Possession Of A Good Fortune, Must Be In Want Of A Wife.",
			eachWordCapitalized);
}
 
Example 29
Source Project: xibalba   Source File: HudRenderer.java    License: MIT License 5 votes vote down vote up
private void updateFocused() {
  if (WorldManager.state == WorldManager.State.FOCUSED) {
    if (focusedTable.getChildren().size == 0) {
      BodyComponent body = ComponentMappers.body.get(playerDetails.focusedEntity);

      int actionNumber = 0;
      for (String part : body.bodyParts.keySet()) {
        actionNumber++;

        // If you look at the docs for Input.Keys, number keys are offset by 7
        // (e.g. 0 = 7, 1 = 8, etc)
        ActionButton button = new ActionButton(actionNumber, WordUtils.capitalize(part));
        button.setKeys(actionNumber + 7);
        button.setAction(bottomTable, () -> handleFocusedAttack(part));
        focusedTable.add(button).pad(5, 0, 0, 0);

        if ((actionNumber & 1) == 0) {
          focusedTable.row();
        }
      }
    }
  } else {
    if (focusedTable.getChildren().size > 0) {
      focusedTable.clear();
    }
  }
}
 
Example 30
Source Project: toolbox   Source File: Attributes.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString(){

    final int FIXED_WIDTH = 80;

    String s = "";
    Iterator<Attribute> it = this.iterator();
    if (it.hasNext()) {
        s += it.next().getName();
    }
    while (it.hasNext()) {
        s += ", " + it.next().getName();
    }
    return(WordUtils.wrap(s+"\n",FIXED_WIDTH));
}