I was first using only getTitle() for this but then found you need to use getView() as well. So i did but I stil can't get it to work.
FYI This is the error :
Cannot resolve method 'getView' in 'Inventory'
I tried changing getInventory() for InventoryView() but still the same error but also the Cannot resolve method 'InventoryView' in 'Chest' error so this means I cant get the inventory view from a block?
#EventHandler
public void onInteract(PlayerInteractEvent e) {
Action a = e.getAction();
Player p = e.getPlayer();
ItemStack hand = e.getItem();
Block clicked = e.getClickedBlock();
if (a != Action.PHYSICAL) {
assert clicked != null;
if(clicked.getType() == Material.CHEST){
hand.getType();
Chest chest = (Chest) clicked.getState();
Inventory inv = chest.getInventory();
if(inv.getView().getTitle().equalsIgnoreCase("Test")) {
p.sendMessage("Event triggered");
e.setCancelled(true);
}
}
}
}
I have figured it out after searching on around 100 sites I found a solution that works, I don't know if it's the best solution but good for me.
I changed the whole event to use InventoryOpenEvent insted of PlayerInteractEvent.
Here is the full code :
#EventHandler
public void onInventoryOpen(InventoryOpenEvent e) {
Player player = (Player) e.getPlayer();
if (e.getView().getTitle().equals("Test")) {
e.setCancelled(true);
player.sendMessage("Succesfull");
}
}
Here is the code stripped down :
#EventHandler
public void onInventoryOpen(InventoryOpenEvent e) {
if (e.getView().getTitle().equals("Test")) {
e.setCancelled(true);
}
}
Related
I have been trying to figure out a way to create a boolean to determine which biome the user chose based on their input using a scanner. But I have not been able to find a way to implement it. I have tried to use boolean return methods but I kept on getting null or the exact opposite biome I was trying to go for.
File: game.java
public boolean isPlains() {
if (biome == "Plains") {
return true;
} else {
return false;
}
}
public boolean isTundra() {
if (biome == "Tundra") {
return true;
} else {
return false;
}
}
File: phase.java
public class phase extends game{
public void battle() {
game gm = new game();
if (isPlains() == true) {
System.out.println("Hello");
} else {
System.out.println("Bye");
}
}
}
Above is the test run I've tried to run, but whenever I try and run the code it seems to output the opposite I ask it to. I tried flipping it around but it seems to do the same thing. I am trying to use the isPlains/isTundra methods from game.java to determine whether to print hello or bye from phase.java.
I struggled to find a solution or at least to point me in the right direction...
Here is my ArrayList: books = new ArrayList();
I have to search objects of Book that contain a title(String). Here is what I have..
The problem being is that I only want to print the second statement if it is not found. But it seems to be printing it as it searches each object in the list?
public void searchBookInCollection(String title)
{
for (Book book : books)
{
if(book.getTitle().equalsIgnoreCase(title))
{
book.displayBookInformation();
}
else
{
System.out.println("Nope we don't have it");
}
}
}
change it to have a boolean found flag
public void searchBookInCollection(String title)
{
boolean found = false;
for (Book book : books)
{
if(book.getTitle().equalsIgnoreCase(title))
{
book.displayBookInformation();
found = true;
break; // no point to keep going?
}
}
if (!found)
{
System.out.println("Nope we don't have it");
}
}
Since the method says searchBookInCollection() it is expected to return a book or a name or something. This gives an alternative solution,
public String findBook(String title) { // "InCollection" does not help end user, "find" follows standard naming convention
for (String book : books) {
if (book.equalsIgnoreCase(title)) {
return book; // This is debated, if you want "one return" here, use temporary variable.
}
}
throw new NoSuchElementException("Title was not found!"); // Throw gives the end user a chance to handle the exception.
}
I have created an ItemStack which should be given to players when they join, but it doesn't work as expected.
Here is my attempt:
public class Main extends JavaPlugin implements Listener{
public void onEnable(){
Bukkit.getServer().getPluginManager().registerEvents(this, this);
registerListeners();
}
private void registerListeners() {
PluginManager pm = Bukkit.getPluginManager();
}
public static void giveItems(Player p) {
}
#EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
Player p = e.getPlayer();
ItemStack t = new ItemStack(Material.TNT, 1);
ItemMeta tmeta = t.getItemMeta();
tmeta.setDisplayName("§cTNT §7(Right click to use)");
t.setItemMeta(tmeta);
for(Player pl : Bukkit.getOnlinePlayers()){
p.getInventory().setItem(4, t);
p.getInventory().addItem(t);
}
}
#SuppressWarnings("deprecation")
#EventHandler
public void onRightClick(PlayerInteractEvent e) {
if(e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
if(e.getItem() != null && e.getItem().getType() == Material.TNT) {
Player p = e.getPlayer();
TNTPrimed tnt = (TNTPrimed) p.getWorld().spawn(p.getLocation(), TNTPrimed.class);
tnt.setVelocity(p.getLocation().getDirection().normalize().multiply(1));
p.updateInventory();
And it failed.
How can I successfully give ItemStacks to Players when they join the server?
Uh, why are you looping through all players in the server when you already have the player you want to give the item to in the variable p? You're also not using proper chat color codes.
Use this instead:
// Imports and other code here...
#EventHandler
public void onPlayerJoin(PlayerJoinEvent e){
Player p = e.getPlayer();
ItemStack t = new ItemStack(Material.TNT);
ItemMeta tmeta = t.getItemMeta();
tmeta.setDisplayName(ChatColor.RED + "TNT " + ChatColor.GRAY + "(Right click to use)");
t.setItemMeta(tmeta);
p.getInventory().addItem(t);
}
Other than that, I don't see anything wrong with your setup.
Looking into your code the following mistakes should be corrected:
Remove the useless method registerLiteners() and all of its calls. The method doesn't really do anything.
You should not interate all online players to add the ItemStack to your Player.
Second of all: from your question, what I can understand as your situation is: you want a player to join the server and receive an item for that. The way you're handling it is that everytime a player joins the server, he will get items added to his inventory for every player online in the server. The situation you're probably in is that you're testing the plugin on your own, and there is no player online when you join, what leads to no items being given.
All things considered, the correct way to get your intended behaviour should be the following:
#EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
Player joined = e.getPlayer();
ItemStack itemToAdd = new ItemStack(Material.TNT);
ItemMeta stackMeta = itemToAdd.getItemMeta();
stackMeta.setDisplayName(ChatColor.RED + "TNT " + ChatColor.GRAY + "(Right click to use)"); //Using ChatColor is recommended over § character.
itemToAdd.setItemMeta(stackMeta);
joined.getInventory().addItem(itemToAdd);
}
The event will add your custom itemstack to the player's inventory after he joins the server.
It's also important to point out that, although it's not part of your question, your PlayerInteractEvent should be fixed to only listen to your custom ItemStack. It will be fired with any TnT held.
I know this question comes up often, but even after looking at asked question's I can't find a solution..
So for school we have to create an own version of World of Zuul. I've implemented a beamer in it. First I put it in the Game class, but I decided it would be better to have it in it's own class, Beamer. The Beamer class looks as follows:
public class Beamer
{
private Room beamerRoom;
private Room beamer;
private int timesFired;
private boolean beamerCharged;
public Beamer(int timesFired, boolean beamerCharged)
{
this.timesFired = 0;
this.beamerCharged = false;
}
public int getTimesFired()
{
return timesFired;
}
public Room getBeamerRoom()
{
return beamerRoom;
}
public boolean getBeamerCharged()
{
return beamerCharged;
}
public Room setBeamerRoom(Room room)
{
this.beamerRoom = Game.getCurrentRoom();
return beamerRoom;
}
/**
* Try to use beamer device. When you charge the beamer, it memorizes the current room.
* When you fire the beamer, it transports you immediately back to the room it was
* charged in.
*/
public void beamer(Command command){
if (!command.hasSecondWord()) {
// if there is no second word, we don't know what to do...
System.out.println("Charge or fire beamer?");
return;
}
String action = command.getSecondWord();
if (action.equals("charge")) {
if(timesFired() < 1)
{
beamerRoom = Game.getCurrentRoom();
System.out.println("This room is charged to beam!");
beamerCharged = true;
}
else
{
System.out.println("The beamer has already been fired and can't be charged again");
}
} else if (action.equals("fire")) {
if(beamerCharged == true)
{
if(timesFired < 1)
{
Game.getCurrentRoom() = beamer.getBeamerRoom();
System.out.println("The beamer has succesfully been fired!");
System.out.println(currentRoom.getLongDescription());
timesFired++;
beamerCharged = false;
}
else
{
System.out.println("You can only fire the beamer once!");
}
}
else
{
System.out.println("The beamer hasn't been charged yet!");
}
} else {
System.out.println("Invalid beamer command!");
return;
}
}
}
I get the error method getCurrentRoom() cannot be referenced from a static context here:
beamerRoom = Game.getCurrentRoom();
The method in Game to get the current room is as follows:
public Room getCurrentRoom()
{
return currentRoom;
}
Very simple, which in my mind should work.
How can I solve this issue? I've looked around but can't find a fix that works..
If you need more of the Game class code, please ask. I didn't post it here since it's 300+ lines.
EDIT:
I already found what I did wrong. By using Game.getCurrentRoom it looked at the class Game, rather than an object of the Game. At least that's what I think went wrong. I had the error message with more methods, using capital letters (Game.<method>), Player.<method>), but when I didn't use the capital letters (game.<method>), player.<method>) it worked fine.
So I guess the problem is solved.
When you call Game.getCurrentRoom() you arer trying to call the method on the class Game. But you defined the method as an instance method. So you either need to change your code to use a singleton instane of Game to access its instance methods, or you need to declare the mehtods on Class as static. Note that those methods again can only access class members, not instance members.
public static Room getCurrentRoom()
{
return currentRoom; // currentRoom has to be declared as a private static class member
}
I currently have code to share a variable between two entry points in my application. The variable is the iconCount variable used to indicate how many notices the user has which is displayed on the home screen beside the icon. The way I've managed to do this is with a singleton and it (seems) to work fine at the moment. The issue is now that I do not want those notices to reset to zero when I completely turn off and turn on the phone. Should there be 7 notifications, I want there to be 7 notifications even after a device restart. For this I apparently need a persistent store integration which I've researched for a while.
So far my code for the bare singleton is:
public class MyAppIndicator{
public ApplicationIndicator _indicator;
public static MyAppIndicator _instance;
MyAppIndicator () {
setupIndicator();
}
public static MyAppIndicator getInstance() {
if (_instance == null) {
_instance = new MyAppIndicator ();
}
return(_instance);
}
public void setupIndicator() {
//Setup notification
if (_indicator == null) {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry.getInstance();
_indicator = reg.getApplicationIndicator();
if(_indicator == null) {
ApplicationIcon icon = new ApplicationIcon(EncodedImage.getEncodedImageResource ("notificationsdemo_jde.png"));
_indicator = reg.register(icon, false, true);
_indicator.setValue(0);
_indicator.setVisible(false);
}
}
}
public void setVisible1(boolean visible, int count) {
if (_indicator != null) {
if (visible) {
_indicator.setVisible(true);
_indicator.setValue(count); //UserInterface.incrementCount()
} else {
_indicator.setVisible(false);
}
}
}
}
I have been using the blackberry tutorial to figure out how to implement the persistable storage: http://supportforums.blackberry.com/t5/Java-Development/Storing-persistent-data/ta-p/442747
Now before I go any further I must stress I'm very new to java development so my coding might be completely wrong, but here is what I've tried to do:
public void setVisible1(boolean visible, int count) {
if (_indicator != null) {
if (visible) {
_indicator.setVisible(true);
_indicator.setValue(count); //UserInterface.incrementCount()
StoreInfo info = new StoreInfo();
info.incElement();
synchronized (persistentCount) {
//persistentCount.setContents(_data);
persistentCount.commit();
}
} else {
_indicator.setVisible(false);
}
}
}
static {
persistentCount = PersistentStore.getPersistentObject(0xdec6a67096f833cL);
synchronized (persistentCount) {
if (persistentCount.getContents() == null) {
persistentCount.setContents(new Vector()); //don't know what to do with this?
persistentCount.commit();
}
}
}
private static final class StoreInfo implements Persistable{
private int iconCount;
public StoreInfo(){}
public int getElement(){
return (int)iconCount;
}
public void incElement(){
iconCount++; //persistently increment icon variable
}
public void resetElement(){
iconCount=0; //when user checks application
}
}
The code above doesn't work which I'd expect somehow because I'm having trouble implementing the persistent portion. If anyone has any idea or input on how to accomplish this any assistance would be helpful. And of course thanks in advance.
In the example they have a variable called _data that holds the StoreInfo class, so first of all you should be keeping the StoreInfo in some variable. To do this have something like the following in your static initializer:
persistentCount = PersistentStore.getPersistentObject(0xdec6a67096f833cL);
synchronized (persistentCount) {
if (persistentCount.getContents() == null) {
persistentCount.setContents(new StoreInfo());
persistentCount.commit();
}
}
_data = (StoreInfo)persistentCount.getContents();
Now when you want to update it and save to the PersistentStore you can have something like:
_data.incElement();
synchronized(persistentCount) {
persistentCount.setContents(_data);
persistentCount.commit();
}
Assuming you're going to only ever have one instance of StoreInfo it could be better to put the commit code into the modifier methods so you don't forget to save the new values to the PersistentStore.