下面列出了怎么用net.minecraft.util.text.ITextComponent的API类实例代码及写法,或者点击链接到github查看源代码。
private List<ITextComponent> resizeContent(List<String> lines)
{
List<ITextComponent> ret = new ArrayList<ITextComponent>();
for (String line : lines)
{
if (line == null)
{
ret.add(null);
continue;
}
ITextComponent chat = ForgeHooks.newChatWithLinks(line, false);
ret.addAll(GuiUtilRenderComponents.splitText(chat, this.listWidth-8, GuiCustomizeWorld.this.fontRenderer, false, true));
}
return ret;
}
@Override
public ItemStack get(){
ItemStack book = new ItemStack(Items.WRITTEN_BOOK, 1);
NBTTagList nbtPages = new NBTTagList();
for(String page : this.pages){
ITextComponent text = new TextComponentString(page);
String json = ITextComponent.Serializer.componentToJson(text);
NBTTagString nbtPage = new NBTTagString(json);
nbtPages.appendTag(nbtPage);
}
book.setTagInfo("pages", nbtPages);
book.setTagInfo("author", new NBTTagString(this.author == null ? "Anonymous" : this.author));
book.setTagInfo("title", new NBTTagString(this.title == null ? "Book" : this.title));
return book;
}
@Override
protected void addDisplayText(List<ITextComponent> textList) {
if (isStructureFormed()) {
MetaTileEntityRotorHolder rotorHolder = getAbilities(ABILITY_ROTOR_HOLDER).get(0);
FluidStack fuelStack = ((LargeTurbineWorkableHandler) workableHandler).getFuelStack();
int fuelAmount = fuelStack == null ? 0 : fuelStack.amount;
ITextComponent fuelName = new TextComponentTranslation(fuelAmount == 0 ? "gregtech.fluid.empty" : fuelStack.getUnlocalizedName());
textList.add(new TextComponentTranslation("gregtech.multiblock.turbine.fuel_amount", fuelAmount, fuelName));
if (rotorHolder.getRotorEfficiency() > 0.0) {
textList.add(new TextComponentTranslation("gregtech.multiblock.turbine.rotor_speed", rotorHolder.getCurrentRotorSpeed(), rotorHolder.getMaxRotorSpeed()));
textList.add(new TextComponentTranslation("gregtech.multiblock.turbine.rotor_efficiency", (int) (rotorHolder.getRotorEfficiency() * 100)));
int rotorDurability = (int) (rotorHolder.getRotorDurability() * 100);
if (rotorDurability > MIN_DURABILITY_TO_WARN) {
textList.add(new TextComponentTranslation("gregtech.multiblock.turbine.rotor_durability", rotorDurability));
} else {
textList.add(new TextComponentTranslation("gregtech.multiblock.turbine.low_rotor_durability",
MIN_DURABILITY_TO_WARN, rotorDurability).setStyle(new Style().setColor(TextFormatting.RED)));
}
}
}
super.addDisplayText(textList);
}
@SuppressWarnings ("unchecked")
private void handleOpenContainer(PacketCustom packet, Minecraft mc) {
ContainerType<?> rawType = packet.readRegistryIdUnsafe(ForgeRegistries.CONTAINERS);
int windowId = packet.readVarInt();
ITextComponent name = packet.readTextComponent();
if (rawType instanceof ICCLContainerType<?>) {
ICCLContainerType<?> type = (ICCLContainerType<?>) rawType;
ScreenManager.getScreenFactory(rawType, mc, windowId, name)//
.map(e -> (ScreenManager.IScreenFactory<Container, ?>) e)//
.ifPresent(screenFactory -> {
Container container = type.create(windowId, Minecraft.getInstance().player.inventory, packet);
Screen screen = screenFactory.create(container, mc.player.inventory, name);
mc.player.openContainer = ((IHasContainer<?>) screen).getContainer();
mc.displayGuiScreen(screen);
});
}
}
@Override
protected void addDisplayText(List<ITextComponent> textList) {
super.addDisplayText(textList);
if (isStructureFormed()) {
textList.add(new TextComponentTranslation("gregtech.multiblock.large_boiler.temperature", currentTemperature, boilerType.maxTemperature));
textList.add(new TextComponentTranslation("gregtech.multiblock.large_boiler.steam_output", lastTickSteamOutput, boilerType.baseSteamOutput));
ITextComponent heatEffText = new TextComponentTranslation("gregtech.multiblock.large_boiler.heat_efficiency", (int) (getHeatEfficiencyMultiplier() * 100));
withHoverTextTranslate(heatEffText, "gregtech.multiblock.large_boiler.heat_efficiency.tooltip");
textList.add(heatEffText);
ITextComponent throttleText = new TextComponentTranslation("gregtech.multiblock.large_boiler.throttle", throttlePercentage, (int)(getThrottleEfficiency() * 100));
withHoverTextTranslate(throttleText, "gregtech.multiblock.large_boiler.throttle.tooltip");
textList.add(throttleText);
ITextComponent buttonText = new TextComponentTranslation("gregtech.multiblock.large_boiler.throttle_modify");
buttonText.appendText(" ");
buttonText.appendSibling(withButton(new TextComponentString("[-]"), "sub"));
buttonText.appendText(" ");
buttonText.appendSibling(withButton(new TextComponentString("[+]"), "add"));
textList.add(buttonText);
}
}
@SubscribeEvent
public static void addInformation(ItemTooltipEvent ev)
{
if (!ConfigManager.SERVER.enableScraping.get() && EnchantmentHelper.getEnchantmentLevel(SurvivalistMod.SCRAPING.get(), ev.getItemStack()) > 0)
{
List<ITextComponent> list = ev.getToolTip();
/*int lastScraping = -1;
for (int i = 0; i < list.size(); i++)
{
if (list.get(i).getFormattedText().startsWith(I18n.format("enchantment.survivalist.scraping")))
{
lastScraping = i;
}
}
if (lastScraping >= 0)
{
list.add(lastScraping + 1, "" + TextFormatting.DARK_GRAY + TextFormatting.ITALIC + I18n.format("tooltip.survivalist.scraping.disabled"));
}*/
list.add(new TranslationTextComponent("tooltip.survivalist.scraping.disabled").func_240701_a_(TextFormatting.DARK_GRAY, TextFormatting.ITALIC));
}
}
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
super.serialize(builder);
if (hasTitle()) {
builder.put(BOOK_TITLE.BUKKIT, title);
}
if (hasAuthor()) {
builder.put(BOOK_AUTHOR.BUKKIT, author);
}
if (hasPages()) {
List<String> pagesString = new ArrayList<String>();
for (ITextComponent comp : pages) {
pagesString.add(CraftChatMessage.fromComponent(comp));
}
builder.put(BOOK_PAGES.BUKKIT, pagesString);
}
if (generation != null) {
builder.put(GENERATION.BUKKIT, generation);
}
return builder;
}
@Override
public List<BaseComponent[]> getPages() {
final List<ITextComponent> copy = ImmutableList.copyOf(CraftMetaBook.this.pages);
return new AbstractList<BaseComponent[]>() {
@Override
public BaseComponent[] get(int index) {
return ComponentSerializer.parse(ITextComponent.Serializer.componentToJson(copy.get(index)));
}
@Override
public int size() {
return copy.size();
}
};
}
public static void handleEditBookEvent(EntityPlayerMP player, ItemStack newBookItem) {
int itemInHandIndex = player.inventory.currentItem;
PlayerEditBookEvent editBookEvent = new PlayerEditBookEvent(player.getBukkitEntity(), player.inventory.currentItem, (BookMeta) CraftItemStack.getItemMeta(player.inventory.getCurrentItem()), (BookMeta) CraftItemStack.getItemMeta(newBookItem), newBookItem.getItem() == Items.WRITTEN_BOOK);
player.world.getServer().getPluginManager().callEvent(editBookEvent);
ItemStack itemInHand = player.inventory.getStackInSlot(itemInHandIndex);
// If they've got the same item in their hand, it'll need to be updated.
if (itemInHand != null && itemInHand.getItem() == Items.WRITABLE_BOOK) {
if (!editBookEvent.isCancelled()) {
if (editBookEvent.isSigning()) {
itemInHand.setItem(Items.WRITTEN_BOOK);
}
CraftMetaBook meta = (CraftMetaBook) editBookEvent.getNewBookMeta();
List<ITextComponent> pages = meta.pages;
for (int i = 0; i < pages.size(); i++) {
pages.set(i, stripEvents(pages.get(i)));
}
CraftItemStack.setItemMeta(itemInHand, meta);
}
// Client will have updated its idea of the book item; we need to overwrite that
Slot slot = player.openContainer.getSlotFromInventory(player.inventory, itemInHandIndex);
player.connection.sendPacket(new SPacketSetSlot(player.openContainer.windowId, slot.slotNumber, itemInHand));
}
}
public GuiDisconnectedOverride(
GuiScreen screen,
String reasonLocalizationKey,
ITextComponent chatComp,
String reason,
double delay) {
super(screen, reasonLocalizationKey, chatComp);
parent = screen;
message = chatComp;
reconnectTime = System.currentTimeMillis() + (long) (delay * 1000);
// set variable 'reason' to the previous classes value
try {
ReflectionHelper.setPrivateValue(
GuiDisconnected.class,
this,
reason,
"reason",
"field_146306_a",
"a"); // TODO: Find obbed mapping name
} catch (Exception e) {
Helper.printStackTrace(e);
}
// parse server return text and find queue pos
}
@Override
protected void clickHeader(int x, int y)
{
int offset = y;
if (logoPath != null) {
offset -= logoDims.height + 10;
}
if (offset <= 0)
return;
int lineIdx = offset / 10;
if (lineIdx >= lines.size())
return;
ITextComponent line = lines.get(lineIdx);
if (line != null)
{
int k = -4;
for (ITextComponent part : line)
{
if (!(part instanceof TextComponentString))
continue;
k += GuiCustomizeWorld.this.fontRenderer.getStringWidth(((TextComponentString)part).getText());
if (k >= x)
{
GuiCustomizeWorld.this.handleComponentClick(part);
break;
}
}
}
}
@Listener
public void renderWorld(EventRender3D event) {
final Minecraft mc = Minecraft.getMinecraft();
if (this.signs.getValue()) {
for (TileEntity te : mc.world.loadedTileEntityList) {
if (te instanceof TileEntitySign) {
final TileEntitySign sign = (TileEntitySign) te;
sign.signText = new ITextComponent[]{new TextComponentString(""), new TextComponentString(""), new TextComponentString(""), new TextComponentString("")};
}
}
}
}
public void openContainer(ServerPlayerEntity player, ITextComponent title) {
ServerUtils.openContainer(player, new SimpleNamedContainerProvider((id, inv, p) -> new ContainerEnderItemStorage(id, inv, EnderItemStorage.this), title),//
packet -> {
freq.writeToPacket(packet);
packet.writeByte(size);
});
}
@Override
public void addInformation(ItemStack stack, @Nullable World world, List<ITextComponent> tooltip, ITooltipFlag flag) {
super.addInformation(stack, world, tooltip, flag);
if (stack.getItem() instanceof UpgradeCard) {
Upgrade upgrade = ((UpgradeCard) stack.getItem()).upgrade;
int cost = upgrade.getCostPerBlock();
if (cost > 0)
tooltip.add(new TranslationTextComponent("mininggadgets.tooltip.item.upgrade_cost", cost).applyTextStyle(TextFormatting.AQUA));
cost = 0;
if (upgrade == Upgrade.LIGHT_PLACER)
cost = Config.UPGRADECOST_LIGHT.get();
if (upgrade == Upgrade.FREEZING)
cost = Config.UPGRADECOST_FREEZE.get();
if (cost > 0)
tooltip.add(new TranslationTextComponent("mininggadgets.tooltip.item.use_cost", cost).applyTextStyle(TextFormatting.AQUA));
if( upgrade.getBaseName().equals(Upgrade.BATTERY_1.getBaseName()) ) {
UpgradeBatteryLevels.getBatteryByLevel(upgrade.getTier()).ifPresent(e -> {
tooltip.add(new TranslationTextComponent("mininggadgets.tooltip.item.battery_boost", MagicHelpers.tidyValue(e.getPower())).applyTextStyle(TextFormatting.AQUA));
});
}
tooltip.add(new TranslationTextComponent(this.upgrade.getTooltop()).applyTextStyle(TextFormatting.GRAY));
}
}
@Override
public void addInformation(ItemStack stack, @Nullable World world, List<ITextComponent> tooltip, ITooltipFlag flag) {
super.addInformation(stack, world, tooltip, flag);
List<Upgrade> upgrades = UpgradeTools.getUpgrades(stack);
Minecraft mc = Minecraft.getInstance();
if (!InputMappings.isKeyDown(mc.getMainWindow().getHandle(), mc.gameSettings.keyBindSneak.getKey().getKeyCode())) {
tooltip.add(new TranslationTextComponent("mininggadgets.tooltip.item.show_upgrades",
mc.gameSettings.keyBindSneak.getLocalizedName().toLowerCase())
.applyTextStyle(TextFormatting.GRAY));
} else {
tooltip.add(new TranslationTextComponent("mininggadgets.tooltip.item.break_cost", getEnergyCost(stack)).applyTextStyle(TextFormatting.RED));
if (!(upgrades.isEmpty())) {
tooltip.add(new TranslationTextComponent("mininggadgets.tooltip.item.upgrades").applyTextStyle(TextFormatting.AQUA));
for (Upgrade upgrade : upgrades) {
tooltip.add(new StringTextComponent(" - " +
I18n.format(upgrade.getLocal())
).applyTextStyle(TextFormatting.GRAY));
}
}
}
stack.getCapability(CapabilityEnergy.ENERGY, null)
.ifPresent(energy -> tooltip.add(
new TranslationTextComponent("mininggadgets.gadget.energy",
MagicHelpers.tidyValue(energy.getEnergyStored()),
MagicHelpers.tidyValue(energy.getMaxEnergyStored())).applyTextStyles(TextFormatting.GREEN)));
}
/**
* Called serverside to obtain text displayed in GUI
* each element of list is displayed on new line
* to use translation, use TextComponentTranslation
*/
protected void addDisplayText(List<ITextComponent> textList) {
if (!isStructureFormed()) {
ITextComponent tooltip = new TextComponentTranslation("gregtech.multiblock.invalid_structure.tooltip");
tooltip.setStyle(new Style().setColor(TextFormatting.GRAY));
textList.add(new TextComponentTranslation("gregtech.multiblock.invalid_structure")
.setStyle(new Style().setColor(TextFormatting.RED)
.setHoverEvent(new HoverEvent(Action.SHOW_TEXT, tooltip))));
}
}
@Override
protected void addDisplayText(List<ITextComponent> textList) {
super.addDisplayText(textList);
if (isStructureFormed()) {
if (!workableHandler.isWorkingEnabled()) {
textList.add(new TextComponentTranslation("gregtech.multiblock.work_paused"));
} else if (workableHandler.isActive()) {
textList.add(new TextComponentTranslation("gregtech.multiblock.running"));
textList.add(new TextComponentTranslation("gregtech.multiblock.generation_eu", workableHandler.getRecipeOutputVoltage()));
} else {
textList.add(new TextComponentTranslation("gregtech.multiblock.idling"));
}
}
}
@SubscribeEvent
public void onPlayerJoin(TickEvent.PlayerTickEvent event){
if(event.player.world.isRemote && event.player == FMLClientHandler.instance().getClientPlayerEntity()) {
event.player.sendMessage(ITextComponent.Serializer.jsonToComponent("[\"" + TextFormatting.GOLD + "The mod " + supportingMod + " is supporting In-Game Wiki mod. " + TextFormatting.GOLD + "However, In-Game Wiki isn't installed! " + "[\"," + "{\"text\":\"Download Latest\",\"color\":\"green\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/igwmod_download\"}}," + "\"]\"]"));
FMLCommonHandler.instance().bus().unregister(this);
}
}
@Override
public ITextComponent getDisplayName() {
final String name = getName();
return hasCustomName()
? new TextComponentString(name)
: new TextComponentTranslation(name);
}
@Override
public List<ITextComponent> getMagnifyResults(IBlockAccess world, BlockPos pos, IBlockState blockState, EntityPlayer player) {
ArrayList<ITextComponent> result = new ArrayList<>();
ITextComponent materialComponent = new TextComponentTranslation(getStoneMaterial(world, pos, blockState).getUnlocalizedName());
materialComponent.getStyle().setColor(TextFormatting.GREEN);
result.add(new TextComponentTranslation("gregtech.block.surface_rock.material", materialComponent));
return result;
}
@Override
public ItemStack onItemUseFinish(ItemStack stack, EntityPlayer player) {
if (!player.world.isRemote) {
Pair<BlockPos, IBlockState> hitBlock = getHitBlock(player);
if (hitBlock != null && checkCanUseScanner(stack, player, false).getLeft() == null) {
ITextComponent component = new TextComponentTranslation("behavior.scanner.analyzing_complete");
component.getStyle().setColor(TextFormatting.GOLD);
player.sendStatusMessage(component, true);
IScannableBlock magnifiableBlock = ((IScannableBlock) hitBlock.getRight().getBlock());
List<ITextComponent> text = magnifiableBlock.getMagnifyResults(player.world, hitBlock.getLeft(), hitBlock.getRight(), player);
text.forEach(player::sendMessage);
}
}
return stack;
}
@Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {
ItemStack itemStack = player.getHeldItem(hand);
if(player.isSneaking()) {
T currentMode = getModeFromItemStack(itemStack);
int currentModeIndex = ArrayUtils.indexOf(enumConstants, currentMode);
T nextMode = enumConstants[(currentModeIndex + 1) % enumConstants.length];
setModeForItemStack(itemStack, nextMode);
ITextComponent newModeComponent = new TextComponentTranslation(nextMode.getUnlocalizedName());
ITextComponent textComponent = new TextComponentTranslation("metaitem.behavior.mode_switch.mode_switched", newModeComponent);
player.sendStatusMessage(textComponent, true);
return ActionResult.newResult(EnumActionResult.SUCCESS, itemStack);
}
return ActionResult.newResult(EnumActionResult.PASS, itemStack);
}
public static ITextComponent[] sanitizeLines(String[] lines) {
ITextComponent[] components = new ITextComponent[4];
for (int i = 0; i < 4; i++) {
if (i < lines.length && lines[i] != null) {
components[i] = CraftChatMessage.fromString(lines[i])[0];
} else {
components[i] = new TextComponentString("");
}
}
return components;
}
public static String[] revertComponents(ITextComponent[] components) {
String[] lines = new String[components.length];
for (int i = 0; i < lines.length; i++) {
lines[i] = revertComponent(components[i]);
}
return lines;
}
@Override
void applyToItem(NBTTagCompound itemData) {
super.applyToItem(itemData, false);
if (hasTitle()) {
itemData.setString(BOOK_TITLE.NBT, this.title);
} else {
itemData.setString(BOOK_TITLE.NBT, " ");
}
if (hasAuthor()) {
itemData.setString(BOOK_AUTHOR.NBT, this.author);
} else {
itemData.setString(BOOK_AUTHOR.NBT, " ");
}
if (hasPages()) {
NBTTagList list = new NBTTagList();
for (ITextComponent page : pages) {
list.appendTag(new NBTTagString(
ITextComponent.Serializer.componentToJson(page)
));
}
itemData.setTag(BOOK_PAGES.NBT, list);
}
itemData.setBoolean(RESOLVED.NBT, true);
if (generation != null) {
itemData.setInteger(GENERATION.NBT, generation);
} else {
itemData.setInteger(GENERATION.NBT, 0);
}
}
CraftMetaBook(NBTTagCompound tag, boolean handlePages) {
super(tag);
if (tag.hasKey(BOOK_TITLE.NBT)) {
this.title = tag.getString(BOOK_TITLE.NBT);
}
if (tag.hasKey(BOOK_AUTHOR.NBT)) {
this.author = tag.getString(BOOK_AUTHOR.NBT);
}
boolean resolved = false;
if (tag.hasKey(RESOLVED.NBT)) {
resolved = tag.getBoolean(RESOLVED.NBT);
}
if (tag.hasKey(GENERATION.NBT)) {
generation = tag.getInteger(GENERATION.NBT);
}
if (tag.hasKey(BOOK_PAGES.NBT) && handlePages) {
NBTTagList pages = tag.getTagList(BOOK_PAGES.NBT, CraftMagicNumbers.NBT.TAG_STRING);
for (int i = 0; i < Math.min(pages.tagCount(), MAX_PAGES); i++) {
String page = pages.getStringTagAt(i);
if (resolved) {
try {
this.pages.add(ITextComponent.Serializer.jsonToComponent(page));
continue;
} catch (Exception e) {
// Ignore and treat as an old book
}
}
addPage(page);
}
}
}
void applyToItem(NBTTagCompound itemData, boolean handlePages) {
super.applyToItem(itemData);
if (hasTitle()) {
itemData.setString(BOOK_TITLE.NBT, this.title);
}
if (hasAuthor()) {
itemData.setString(BOOK_AUTHOR.NBT, this.author);
}
if (handlePages) {
if (hasPages()) {
NBTTagList list = new NBTTagList();
for (ITextComponent page : pages) {
list.appendTag(new NBTTagString(CraftChatMessage.fromComponent(page)));
}
itemData.setTag(BOOK_PAGES.NBT, list);
}
itemData.removeTag(RESOLVED.NBT);
}
if (generation != null) {
itemData.setInteger(GENERATION.NBT, generation);
}
}
@Override
public void setPage(final int page, final BaseComponent... text) {
if (!isValidPage(page)) {
throw new IllegalArgumentException("Invalid page number " + page + "/" + pages.size());
}
BaseComponent[] newText = text == null ? new BaseComponent[0] : text;
CraftMetaBook.this.pages.set(page - 1, ITextComponent.Serializer.jsonToComponent(ComponentSerializer.toString(newText)));
}
@Override
public void addPage(final BaseComponent[]... pages) {
for (BaseComponent[] page : pages) {
if (CraftMetaBook.this.pages.size() >= MAX_PAGES) {
return;
}
if (page == null) {
page = new BaseComponent[0];
}
CraftMetaBook.this.pages.add(ITextComponent.Serializer.jsonToComponent(ComponentSerializer.toString(page)));
}
}
protected CompoundNBT write_internal(CompoundNBT tagCompound) {
tagCompound.putInt("left", left.getWoolMeta());
tagCompound.putInt("middle", middle.getWoolMeta());
tagCompound.putInt("right", right.getWoolMeta());
if (owner != null) {
tagCompound.putUniqueId("owner", owner);
}
if (ownerName != null) {
tagCompound.putString("owner_name", ITextComponent.Serializer.toJson(ownerName));
}
return tagCompound;
}