Interactive Books

Jul 9, 2018
Interactive Books
  • Interactive Books

    How to create a book with click and hover events



    This is how you can create a book with click and hover events.


    Creating the Book(top)

    To begin with, we will need to obtain the BookMeta from a ItemStack. Only an ItemStack with Material.BOOK_AND_QUILL or Material.WRITTEN_BOOK have this.
    Code (Java):
    ItemStack book = new ItemStack(Material.WRITTEN_BOOK);
    BookMeta bookMeta = (BookMeta) book.getItemMeta();

    Getting the Pages(top)

    BookMeta is the Bukkit interface for the CraftMetaBook object in CraftBukkit. Bukkit itself does not include methods to access the component messages but the Spigot API adds a helpfull BookMeta.Spigot class which contains methods to work with the Bungee-Chat API's BaseComponents which are included in Spigot.
    Code (Java):
    List<BaseComponent[]> pages = bookMeta.spigot().getPages();
    Any changes we make to this list will not update the book and so we need to set them again after we are done with it!
    Code (Java):
    bookMeta.spigot().setPages(pages);

    Creating a Page With Click/Hover Events(top)

    Using the BungeeCord chat component API (which is included in the spigot server jar) you can produce a BaseComponent array which contains click and hover events and add it to the list of pages:
    Code (Java):
    pages.add(page);
    bookMeta.setPages(pages);
    Alternatively you can add a new page directly to the BookMeta:
    Code (Java):
    bookMeta.spigot().addPage(page);
    Or set a specific one:
    Code (Java):
    bookMeta.spigot().setPage(number, page); // page numbers start at 1

    Finish Creating the ItemStack(top)

    Once you've finished adding the pages, don't forget to add this new BookMeta to the original ItemStack! You can also set a title and an author for the book.
    Code (Java):
    bookMeta.setTitle("Interactive Book");
    bookMeta.setAuthor("gigosaurus");

    book.setItemMeta(bookMeta);

    An Example Book(top)

    Code (Java):
    //create the book
    ItemStack book = new ItemStack(Material.WRITTEN_BOOK);
    BookMeta bookMeta = (BookMeta) book.getItemMeta();

    //create a page
    BaseComponent[] page = new ComponentBuilder("Click me")
            .event(new ClickEvent(ClickEvent.Action.OPEN_URL, "http://spigotmc.org"))
            .event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Go to the spigot website!").create()))
            .create();

    //add the page to the meta
    bookMeta.spigot().addPage(page);

    //set the title and author of this book
    bookMeta.setTitle("Interactive Book");
    bookMeta.setAuthor("gigosaurus");

    //update the ItemStack with this new meta
    book.setItemMeta(bookMeta);
  • Loading...
  • Loading...