This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I has an error if players use ShopGUI+ Plugin to buy or sell, it will error in consoler! Plugin ShopGUI+:
https://www.spigotmc.org/resources/shopgui.6515/ Error console: http://pastebin.com/Q1Hjssfm Please help me. Thanks!
class: package com.andrewyunt.townygui.listeners;
import com.andrewyunt.townygui.Menu;
import com.andrewyunt.townygui.TownyGUI;
import com.andrewyunt.townygui.utilities.CommandBuilder;
import com.gmail.filoghost.hiddenstring.HiddenStringUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.List;
import java.util.Set;
public class InventoryListener implements Listener {
#EventHandler
public void onInventoryClick(InventoryClickEvent sukien) {
ItemStack item = sukien.getCurrentItem();
Player player = (Player) sukien.getWhoClicked();
if(!(sukien.getInventory().getHolder() == null))
return;
if(item == null || !item.hasItemMeta())
return;
ItemMeta meta = item.getItemMeta();
List<String> lore = meta.getLore();
if(!HiddenStringUtils.hasHiddenString(lore.get(0)))
return;
String action = HiddenStringUtils.extractHiddenString(lore.get(0));
boolean command;
command = action.startsWith("/");
if(!command)
new Menu(player, action);
else {
player.closeInventory();
Set<String> arguments;
try {
arguments = TownyGUI.plugin.commandConfig.getConfig().getConfigurationSection("commands."+ action + ".arguments").getKeys(false);
} catch(NullPointerException e) {
action = action.replace("/", "");
TownyGUI.plugin.server.dispatchCommand(player, action);
sukien.setCancelled(true);
return;
}
new CommandBuilder(arguments, action).beginConversation((CommandSender) player);
}
sukien.setCancelled(true);
} }
As far as the NullPointerException you provided goes, this is the line that causes the error:
String action = HiddenStringUtils.extractHiddenString(lore.get(0));
You should be able to check why it results in a NullPointerException.
I guess the event-error you get will be resolved as soon as you fix your code.
Also the first link you provided does not work without being logged in.
Related
This question already has an answer here:
Cannot resolve method 'getTitle' in 'Inventory' when click event
(1 answer)
Closed 6 days ago.
Im trying to make a minecraft anti cheat with bukkit. my server version is 1.18.
but i seem to get this error;
java: cannot find symbol symbol: method getTitle() location: variable inventory of type org.bukkit.inventory.Inventory
here is the segment of code that error is referring about;
if (inventory.getTitle().equals("Flagged Players")) {
full segment of code (Not entire file of code):
package anticheat.anticheat;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.event.player.PlayerMoveEvent;
public class Anticheat implements Listener {
private Map<Player, Boolean> flaggedPlayers = new HashMap<>();
private Map<Player, Inventory> flaggedPlayersInventory = new HashMap<>();
#EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
if (isUsingFlyHack(player)) {
// Flag the player and kick them from the server
flagPlayer(player);
player.kickPlayer("Using fly hacks is not allowed on this server");
}
}
#EventHandler
public void onInventoryClick(InventoryClickEvent event) {
Player player = (Player) event.getWhoClicked();
Inventory inventory = event.getInventory();
if (inventory.getType() == InventoryType.CHEST) {
if (inventory.getTitle().equals("Flagged Players")) {
ItemStack item = event.getCurrentItem();
SkullMeta meta = (SkullMeta) item.getItemMeta();
Player flaggedPlayer = Bukkit.getPlayer(meta.getOwningPlayer().getName());
// Check if the clicked item is a player head
if (item.getType() == Material.PLAYER_HEAD && flaggedPlayers.get(flaggedPlayer) != null) {
}
event.setCancelled(true);
}
}
}
I have tried to replace .getTitle with .getName using the code bellow
if (inventory.getTitle().equals("Flagged Players")) {
But that didn't fix it and gave me the same error.
**I have also tried **
if (inventory.getType() == InventoryType.CHEST && inventory.getTitle().equals("Flagged Players")) {
But also gave me the same output.
The method getTitle was removed from Inventory.
You can access that value in your code using:
event.getView().getTitle()
I am trying to make a plugin where when a certain block in the GUI is clicked, a command is run. The problem is, I have to transfer a string from one method to another. I don't have very much java knowledge, so if someone could teach me how to do this, I would very much appreciate it.
P.S. The string I am trying to use is called custompermscommand.
Code:
package me.eliminiquated.yugengrant;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
public class Grant implements CommandExecutor, Listener {
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("grant")){
if (sender instanceof Player){
Player player = (Player) sender;
if (player.hasPermission("yugen.grant")){
if (args.length == 1){
player.sendMessage("Incorrect Usage! </grant (username)>");
}else if (args.length == 2){
Inventory gui = Bukkit.createInventory(player, 27, ChatColor.DARK_GREEN+"Grant Menu");
ItemStack custom = new ItemStack(Material.ORANGE_GLAZED_TERRACOTTA);
ItemStack playerranks = new ItemStack(Material.LAPIS_BLOCK);
ItemStack staffpositions = new ItemStack(Material.REDSTONE_BLOCK);
ItemMeta custommeta = custom.getItemMeta();
ItemMeta playerranksmeta = playerranks.getItemMeta();
ItemMeta staffpositionsmeta = staffpositions.getItemMeta();
custommeta.setDisplayName(ChatColor.GOLD+"Custom");
ArrayList<String> custom_lore = new ArrayList<>();
custom_lore.add(ChatColor.GRAY+""+ChatColor.ITALIC+"Coming soon");
custommeta.setLore(custom_lore);
custom.setItemMeta(custommeta);
playerranksmeta.setDisplayName(ChatColor.AQUA+"Player Ranks");
playerranks.setItemMeta(playerranksmeta);
staffpositionsmeta.setDisplayName(ChatColor.RED+"Staff Positions");
staffpositions.setItemMeta(staffpositionsmeta);
gui.setItem(10, custom);
gui.setItem(12, playerranks);
gui.setItem(14, staffpositions);
player.openInventory(gui);
String custompermscommand = "grantcustomperms "+args[0]+"";
}else{
player.sendMessage("Incorrect Usage! </grant (username)>");
}
}else{
player.sendMessage(ChatColor.RED+"You do not have permission to execute this command!");
}
}
}else{
System.out.println("You must be a player to execute this command");
}
return false;
}
#EventHandler
public void onInventoryClick(InventoryClickEvent event){
Player player = (Player) event.getWhoClicked();
if (event.getClickedInventory().getTitle().equalsIgnoreCase(ChatColor.DARK_GREEN+"Grant Menu")){
if (event.getCurrentItem().getType() == Material.ORANGE_GLAZED_TERRACOTTA){
Bukkit.dispatchCommand(player, custompermscommand);
}
}
}
}
For anyone that wants to do this themselves, this is the answer:
First, declare the variable as public outside of the methods:
Example:
public String command;
Next, edit the string inside of the method that you want to grab the string from:
Example:
command = args[0];
Finally, you are able to call this string in whatever method you want:
Example:
Bukkit.dispatchCommand(player, command);
I have made a plugin that is supposed to track the amount of diamonds you have mined in Minecraft and save it to a config.yml file. But my code doesn't seem to be working and I cant figure out why?
I've already tried +1 in the setConfig args and now I've switched over to this and it still doesn't seem to be working. I also have diamonds predefined in my config.yml file.
package com.raidoxe.BlockPlugin;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
#Override
public void onEnable() {
getLogger().info("Sartu has been enabled :)");
PluginManager pm = getServer().getPluginManager();
SartuListener listener = new SartuListener(this);
pm.registerEvents(listener, this);
this.getConfig().options().copyDefaults(true);
this.saveConfig();
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = (Player) sender;
if (sender instanceof Player) {
String lowerCmd = cmd.getName().toLowerCase();
switch (lowerCmd) {
case "mydiamonds":
int a = this.getConfig().getInt("diamonds."+player.getUniqueId());
player.sendMessage(ChatColor.DARK_PURPLE+"You have mined "+ChatColor.RED+a+ChatColor.AQUA+" Diamonds");
return true;
}
}
return true;
}
------------Listener File-----------
package com.raidoxe.BlockPlugin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.Plugin;
public class SartuListener implements Listener {
private Plugin plugin = Main.getPlugin(Main.class);
public SartuListener(Main plugin) {
}
#EventHandler
public void blockBreak(BlockBreakEvent event) {
Player player = (Player) event.getPlayer();
Block block = event.getBlock();
Material blockMaterial = block.getType();
if(blockMaterial.equals(Material.DIAMOND_ORE)) {
Bukkit.broadcastMessage(ChatColor.WHITE+player.getDisplayName()+" found a "+ ChatColor.AQUA + ChatColor.BOLD+"Diamond!!!");
int a = plugin.getConfig().getInt("diamonds."+player.getUniqueId());
plugin.getConfig().set("diamonds."+player.getUniqueId(), a++);
plugin.saveConfig();
}
}
when the player does the command /mydiamonds it should print out, "you have mined (a) diamonds". But it always prints out zero, no matter how many diamonds you have mined.
Your code seems to be looking fine except one minor mistake. You say that you've tried +1 in the setConfig, so if this solution does not work for you it's probably a version thing
If a config getInt() returns 0 it can mean two things:
value does not exist (default is returned)
value is actually 0 in the config
Upon testing the value does exist in the config (due to saveConfig(), but is set to 0. So this lead me to the setting method.
The issue is the adding part. You do a++ inside the method, this will increment the number after the method, we want before, switch to ++a. See this post.
if(blockMaterial.equals(Material.DIAMOND_ORE)) {
Bukkit.broadcastMessage(ChatColor.WHITE+player.getDisplayName()+" found a "+ ChatColor.AQUA + ChatColor.BOLD+"Diamond!!!");
int a = plugin.getConfig().getInt("diamonds."+player.getUniqueId());
plugin.getConfig().set("diamonds."+player.getUniqueId(), ++a);
plugin.saveConfig();
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I'm in the process of writing a program, and I get to the part(which I've commented below) and I try to do
if(userInput.get() != "")
It still executes the code inside the if statement if I leave the dialog box blank and press "ok" or enter. So it would say:
"You did not enter numeric information"
instead of
"You did not enter any information"
like in the outer else statement.
I tried with null and it didn't work either. What am I doing wrong here?
import java.util.Optional;
import javafx.application.*;
import javafx.event.*;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.text.*;
import javafx.stage.*;
import javafx.stage.Stage;
public class QuizDialogBox extends Application {
public void start(Stage primaryStage) {
TextInputDialog inputDialog = new TextInputDialog();
inputDialog.setHeaderText(null);
inputDialog.setTitle("Grams to Ounces");
inputDialog.setContentText("Enter number of Grams: ");
Alert errorAlert = new Alert(AlertType.ERROR);
Optional<String> userInput = inputDialog.showAndWait();
if((userInput.get() != "") && userInput.isPresent()) //the part thats not working
{
String userInputString = userInput.get();
System.out.println("{" + userInputString + "}");
if(isNumeric(userInputString))
{
int userNumber = Integer.parseInt(userInputString);
System.out.println(userNumber);
}
else
{
errorAlert.setContentText("You did not enter numeric information");
errorAlert.showAndWait();
}
}
else
{
errorAlert.setContentText("You did not enter any information");
errorAlert.showAndWait();
}
}
public static void main(String args[]) {
launch(args);
}
public static boolean isNumeric(String string) {
boolean isNumber = false;
try
{
Integer.parseInt(string);
isNumber = true;
}
catch(NumberFormatException ex) {
}
return isNumber;
}
}
modify if(userInput.get() != "") to if(!userInput.get().isEmpty())
== compares the reference only.
Or you can use if(!userInput.get().equals("")) to compare two String
Be careful of checking null if userInput.get() is Nullable
This question already has an answer here:
How to solve "NoClassDefFoundError"?
(1 answer)
Closed 6 years ago.
I'm trying to get an program that I coded to run properly. So far it will javac and java fine, however I get a NoClassDefFoundError.
This screenshot shows how I've javac, java the program, and the command prompt report.
As you can see I have 3 source files, and therefore 3 classes. PeriodicTable doesn't do anything related to the issue.
Inside of class Table I have...
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.json.JsonArray;
import javax.json.JsonObject;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.Dimension;
import java.io.IOException;
class Table {
//Predefining some global variables
DataBaseReader dbReader;
//some methods...
protected void showLayout() {
dbReader = new DataBaseReader();
//A few lines of code
try {
JsonArray elements = dbReader.readDataBase(); //Here it enters the DataBaseReader class through dbReader
//Some more code
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
Here is my DataBaseReader class
import javax.json.Json;
import javax.json.JsonReader;
import javax.json.JsonObject;
import javax.json.JsonArray;
import java.io.FileReader;
import java.io.IOException;
public class DataBaseReader
{
public JsonArray readDataBase() throws IOException {
System.out.println("Check!"); //This check is reached
JsonReader reader = Json.createReader(new FileReader("C:/projects/PeriodicTable/Elements.JSON"));
System.out.println("Check!"); //This check is not reached
JsonObject jsonst = reader.readObject();
reader.close();
return jsonst.getJsonArray("Elements");
}
}
What versions, programs, etc am I using?
Java 8
Command Prompt
Notepad
javax.json-1.0.jar
To clearly state my question... Any ideas or explanations about what is causing this error?
i think you are missing javax.json-api-1.0.jar file