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);
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 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:
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.
Now that I have changed the 'Commands' to 'commands' in the plugin.yml I get another error in my cmd when I run my server. The error says '.Jar file does not contain plugin.yml'.
This is my plugin.yml as of now:
name: Wand
version: 1.0
main: me.Pixel.Main
commands:
wand:
And this is my Main file currently:
package me.Pixel;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
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.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin implements Listener {
public Main plugin;
public List<String> spells = new ArrayList<String>();
public getTargets getTargets = new getTargets();
public Spark spark = new Spark(this);
public PoisonWave poisonwave = new PoisonWave(this);
public DarkSpark darkSpark = new DarkSpark(this);
#Override
public void onEnable() {
plugin = this;
getServer().getPluginManager().registerEvents(this, this);
spells.add("Spark");
spells.add("PoisonWave");
spells.add("DarkSpark");
}
#Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if(label.equalsIgnoreCase("wand")) {
if(!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You need to be an in-game player to perform this action!");
} else {
Player p = (Player) sender;
if(sender.hasPermission("wand.wand")) {
ItemStack stack = new ItemStack(Material.BLAZE_ROD);
ItemMeta stackMeta = stack.getItemMeta();
stackMeta.setDisplayName(ChatColor.RED + "Empire Wand");
stack.setItemMeta(stackMeta);
p.getInventory().addItem(stack);
ChatUtilities.sendMessage(p, "You have got yourself a powerful Empire Wand!");
} else {
ChatUtilities.sendMessage(p, ChatColor.RED + "ERROR: No Permission!");
}
}
}
return false;
}
#EventHandler
public void onClick(PlayerInteractEvent e) {
if((e.getAction() == Action.RIGHT_CLICK_AIR) || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
Player p = e.getPlayer();
ItemStack stack = p.getItemInHand();
if(stack != null && stack.getType() == Material.BLAZE_ROD && stack.hasItemMeta() && stack.getItemMeta().getDisplayName().equals(ChatColor.RED + "Empire Wand")) {
int SpellSelected = stack.getDurability();
if(SpellSelected < 2) {
stack.setDurability((short) (SpellSelected + 1));
p.getWorld().playEffect(p.getLocation(), Effect.STEP_SOUND, 119, 30);
} else {
stack.setDurability((short) 0);
}
ChatUtilities.sendMessage(p, "Selected: " + spells.get(SpellSelected));
}
}
if(e.getAction() == Action.LEFT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_BLOCK) {
Player p = e.getPlayer();
ItemStack stack = p.getItemInHand();
if(stack != null && stack.getType() == Material.BLAZE_ROD && stack.hasItemMeta() && stack.getItemMeta().getDisplayName().equals(ChatColor.RED + "Empire Wand")) {
int SpellSelected = stack.getDurability();
if(SpellSelected == 1) {
this.spark.onCast(p);
} else if (SpellSelected == 0) {
this.poisonwave.onCast(p);
}
}
}
}
}
name: Wand
version: 1.0
main: me.Pixel.Main
commands:
wand:
Your plugin.yml file isn't valid. 'commands' must be all lower case, and there must be 2 spaces before wand.
Also, you should not make commands that way. You should make external classes implementing the CommandExecutor Interface.
I think, if you do it this way, I think you must register the command.
Like this:
getCommand("wand").setExecutor(this);
The plugin.yml file is case senstitive, the name of the list of commands needs to be all lowercase (commands instead of Commands). Since you currently have it capitalized, Bukkit/Spigot doesn't register any commands thus resulting in an "Unknown command. Type "/help" for help." message if you test the /wand command (I'm assuming this is the error you're getting, as you didn't describe the problem nor the expected behavior, but this is what happened when I tested the code, and correcting the name of the commands list made the command execute).
You might need to update the player's inventory after adding the item with p.updateInventory(). In your case, it would be something like this:
p.getInventory().addItem(stack);
p.updateInventory();
I am remaking part of a game in Java, and I need to know how to play the MIDI sound files. Preferably it would not involve importing any external libraries. It must also be runnable in a new thread, so that I can stack the individual sounds over the background song.
Thanks for your thoughts and time.
This code plays two MIDI tracks at the same time (the 2nd sequence starts as soon as the 1st dialog is dismissed). No threads are explicitly created, but I imagine it would work much the same if they were wrapped in a Thread object.
import java.net.URL;
import java.util.Locale;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Transmitter;
import javax.swing.JOptionPane;
import org.apache.commons.lang.StringUtils;
class PlayMidi {
public static boolean useExternalSynth = false;
public static void main(String[] args) throws Exception {
MidiDevice receivingDevice = getReceivingDevice();
receivingDevice.open();
URL url1 = new URL("http://pscode.org/media/EverLove.mid");
Sequence sequence1 = MidiSystem.getSequence(url1);
Sequencer sequencer1 = MidiSystem.getSequencer(false);
Transmitter tx1 = sequencer1.getTransmitter();
Receiver rx1 = receivingDevice.getReceiver();
tx1.setReceiver(rx1);
sequencer1.open();
sequencer1.setSequence(sequence1);
URL url2 = new URL("http://pscode.org/media/AftrMdnt.mid");
Sequence sequence2 = MidiSystem.getSequence(url2);
Sequencer sequencer2 = MidiSystem.getSequencer(false);
Transmitter tx2 = sequencer2.getTransmitter();
Receiver rx2 = receivingDevice.getReceiver();
tx2.setReceiver(rx2);
sequencer2.open();
sequencer2.setSequence(sequence2);
sequencer1.start();
JOptionPane.showMessageDialog(null, "Everlasting Love");
sequencer2.start();
JOptionPane.showMessageDialog(null, "After Midnight");
}
private static MidiDevice getReceivingDevice()
throws MidiUnavailableException {
for (MidiDevice.Info mdi: MidiSystem.getMidiDeviceInfo()) {
MidiDevice dev = MidiSystem.getMidiDevice(mdi);
if (dev.getMaxReceivers() != 0) {
String lcName =
StringUtils.defaultString(mdi.getName())
.toLowerCase(Locale.ENGLISH);
if (lcName.contains(useExternalSynth? "usb": "java")) {
return dev;
}
}
}
return null;
}
}