Cannot spawn falling blocks in minecraft - java

So I'm trying to make SEA_LANTERN drop multiple sand underneath of itself when it's placed so I can keep my cannon filled with sand as it's firing here is my code
Main
package me.zavage.sandbot;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import me.zavage.sandbot.commands.SandBotCommand;
import me.zavage.sandbot.listeners.SandBotListener;
public class Main extends JavaPlugin {
#Override
public void onEnable() {
new SandBotListener(this);
new SandBotCommand(this);
}
public static Plugin getInstance() {
return null;
}
}
package me.zavage.sandbot.listeners;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.FallingBlock;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
import me.zavage.sandbot.Main;
public class SandBotListener implements Listener {
private BukkitTask task;
private int keepToSpawn = 0;
public SandBotListener(Main main) {
}
#EventHandler
public void onPlaceSandbot(BlockPlaceEvent e) {
Material spawnType = e.getBlockPlaced().getType(); // get placed block
if(!spawnType.equals(Material.SEA_LANTERN)) // in your case, be sure it's sea lantern
return;
keepToSpawn = 5; // amount of spawned item
Location loc = e.getBlock().getLocation(); // location where entity will spawn
task = Bukkit.getScheduler().runTaskTimer(Main.getInstance(), () -> {
// each 0.5s, we made spawn a falling block of given type
run(loc, spawnType);
if(keepToSpawn == 0)
task.cancel();
keepToSpawn--;
}, 10, 10); // 10 ticks = 0.5 seconds
}
#SuppressWarnings("deprecation")
private void run(Location loc, Material type) {
FallingBlock falling = loc.getWorld().spawnFallingBlock(loc, Material.SAND, (byte) 0);
falling.setDropItem(true);
falling.setVelocity(new Vector(0, -0.5, 0)); // set the velicoty of the block
}
}
Edit: I updated the code including the main class as well
Theres gotta be something I'm missing, but ive tried so many different things at this point

This is an example code that will make spawn 5 times a falling block to below :
private BukkitTask task;
private int keepToSpawn = 0;
#EventHandler
public void onPlaceSandbot(BlockPlaceEvent e) {
Material spawnType = e.getBlockPlaced().getType(); // get placed block
if(!spawnType.equals(Material.SEA_LANTERN)) // in your case, be sure it's sea lantern
return;
keepToSpawn = 5; // amount of spawned item
Location loc = e.getBlock().getLocation(); // location where entity will spawn
task = Bukkit.getScheduler().runTaskTimer(Main.getInstance(), () -> {
// each 0.5s, we made spawn a falling block of given type
run(loc, spawnType);
if(keepToSpawn == 0)
task.cancel();
keepToSpawn--;
}, 10, 10); // 10 ticks = 0.5 seconds
}
#SuppressWarnings("deprecation")
private void run(Location loc, Material type) {
FallingBlock falling = loc.getWorld().spawnFallingBlock(loc, type, (byte) 0);
falling.setDropItem(true);
falling.setVelocity(new Vector(0, -0.5, 0)); // set the velicoty of the block
}
Don't use Bukkit.getWorld(e.getBlockPlaced().getLocation().getWorld().getUID()), you already have the world instance with e.getBlockPlaced().getWorld().
For the Vector used as velocity, you should set the direction of the block. I set negative Y to make it fall (and not x/z to make it keep at his block).
PS: Don't forget to register the listener with this code in your onEnable:
getServer().getPluginManager().registerEvents(new SandBotListener(this), this);
For the instance of your plugin, you have to have an instance of the object "Main" which is represented by "this".
To use it, in your Main.java :
private static Main instance; // create variable that is "static".
// It means it not depend to an object to get it
public static Main getInstance() { // get the object instance, so the plugin instance
return instance;
}
#Override
public void onEnable() {
instance = this; // here set the instance of this, so as the current object
// it will make this object available for everyone
getServer().getPluginManager().registerEvents(new SandBotListener(), this);
}
Then, you can remove the constructor of the SandBotListener.java.
Now, you able to use Main.getInstance().

Related

Can I use the original class as a type and still use its subclasses?

I was working on this code and I happened to put the type as the original class. Now if I plug the variable in with its subclasses (extended classes) it errors. I'm running a Spigot plugin, but obviously this problem has nothing to do with Spigot itself but rather my lack of knowledge regarding Java.
I can't come up with any single solution and I've looked all over.
Edit (My Explaination): If you look at the PlayerClass, you will see a variable called Kit, it uses the KitClass type. If you look at the KitClass it is a class that has one subclass called Alchemist. My question is, does the KitClass type encompass all the inherited classes and original class? If not then what type/modifications would I have to use for the Kit variable within PlayerClass in order for it to allow an instance of the Alchemist class to be set as the Kit variable?
package me.kckeith.KitPvP;
import org.bukkit.entity.Player;
public class PlayerClass {
public Player Player;
public double Coins;
public KitClass Kit;
public PlayerClass(Player Player, double Coins, KitClass Kit) {
this.Player = Player;
this.Coins = Coins;
this.Kit = Kit;
}
public void setKit(KitClass Kit) {
this.Kit = Kit;
this.Kit.giveStuff();
}
}
package me.kckeith.KitPvP;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import net.md_5.bungee.api.ChatColor;
public class KitClass {
public Player Player;
public Material InventoryIcon;
public KitClass(Player player) {
this.Player = player;
}
public void giveStuff() {
Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.GOLD + "Given items!");
}
}
package me.kckeith.KitPvP.Kits;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import me.kckeith.KitPvP.KitClass;
public class Alchemist extends KitClass {
public static Material InventoryIcon = Material.SPLASH_POTION;
public Alchemist(Player player) {
super(player);
}
public void giveStuff() {
// Clear items
this.Player.getInventory().clear();
// Give the player their armor
ItemStack[] Armor = new ItemStack[4];
Armor[0] = new ItemStack(Material.LEATHER_BOOTS);
Armor[1] = new ItemStack(Material.LEATHER_LEGGINGS);
Armor[2] = new ItemStack(Material.LEATHER_CHESTPLATE);
Armor[3] = new ItemStack(Material.LEATHER_HELMET);
// Add Enchants
Armor[0].addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
Armor[1].addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
Armor[2].addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
Armor[3].addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
// Give Armor
this.Player.getInventory().setArmorContents(Armor);
// Give Golden Sword
ItemStack GoldenSword = new ItemStack(Material.GOLDEN_SWORD);
GoldenSword.addEnchantment(Enchantment.DURABILITY, 1);
this.Player.getInventory().addItem(GoldenSword);
// Give Regen Potions
ItemStack RegenPotion = new ItemStack(Material.POTION, 4);
PotionMeta RegenPotionMeta = (PotionMeta) RegenPotion.getItemMeta();
RegenPotionMeta.addCustomEffect(new PotionEffect(PotionEffectType.REGENERATION, 20, 2), true);
RegenPotion.setItemMeta(RegenPotionMeta);
this.Player.getInventory().addItem(RegenPotion);
// Give Damage Potions
ItemStack DamagePotion = new ItemStack(Material.SPLASH_POTION, 8);
PotionMeta DamagePotionMeta = (PotionMeta) DamagePotion.getItemMeta();
DamagePotionMeta.addCustomEffect(new PotionEffect(PotionEffectType.HARM, 0, 2), true);
DamagePotion.setItemMeta(DamagePotionMeta);
this.Player.getInventory().addItem(DamagePotion);
super.giveStuff();
}
}
The specific error I believe was NullStackException however I am not sure. I got into more detail into this issue at the top of the code.
My question is does the KitClass type encompass all the inherited classes and original class?
Yes it does, so when you create an Alchemist you can still use all of the KitClass methods. This would be correct: Alchemist myAlchemistObject = new Alchemist(myPlayer);
You have a lot of code that may be confusing. You should not have a Class and an object/variable with the same name.
For example, when declaring a variable this is not good:
public Player Player;
But this is clear and easy to read:
public Player player;
This is better again, and there will be no mixup/confusion:
public Player myPlayer;
Another example. This is unclear:
PlayerClass PlayerClass = MainClass.PlayerList.get(Player.getUniqueId());
Alchemist Alchemist = new Alchemist(Player);
PlayerClass.Kit = Alchemist;
PlayerClass.Kit.giveStuff();
And this is easy to understand:
PlayerClass myPlayerObject = MainClass.PlayerList.get(myPlayer.getUniqueId());
Alchemist myAlchemistObject = new Alchemist(myPlayer);
myPlayerObject.Kit = myAlchemistObject;
myPlayerObject.Kit.giveStuff();

Calling a Method That Takes a Parameter Within ActionListener

I've encountered a problem while trying to call a method within a class that implements actionListener. The method being called, DataCompiler, needs to use the integer wordCountWhole, which is returned in the wordCount class. The problem is that I can't pass the required parameter to the actionListener method.
import javax.swing.*;
import java.awt.*;
import java.awt.List;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.text.BreakIterator;
import java.util.*;
import java.util.stream.IntStream;
public class GUI extends JFrame {
public JTextArea textInput;
public JButton dataButton;
public String str;
public GUI() {
super("Text Miner");
pack();
setLayout(null);
dataButton = new JButton("View Data"); //Button to take user to data table
dataButton.setSize(new Dimension(120, 50));
dataButton.setLocation(5, 5);
Handler event = new Handler(); //Adds an action listener to each button
dataButton.addActionListener(event);
add(dataButton);
public class wordCount {
public int miner() {
//This returns an integer called wordCountWhole
}
}
public class Handler implements Action { //All the possible actions for when an action is observed
public void action(ActionEvent event, int wordCountWhole) {
if (event.getSource() == graphButton) {
Graphs g = new Graphs();
g.Graphs();
} else if (event.getSource() == dataButton) {
DataCompiler dc = new DataCompiler();
dc.Data(wordCountWhole);
} else if (event.getSource() == enterButton) {
wordCount wc = new wordCount();
sentenceCount sc = new sentenceCount();
wc.miner();
sc.miner();
}
}
}
}
And here's the code for the DataCompiler class:
public class DataCompiler{
public void Data(int wordCountWhole){
int m = wordCountWhole;
System.out.println(m);
}
}
You don't add the parameter there because you've invalidated the contract of the interface.
Use a constructor* (see note below, first)
public class Handler implements Action{ //All the possible actions for when an action is observed
private int wordCountWhole;
public Handler(int number) { this.wordCountWhole = number; }
#Override
public void actionPerformed(ActionEvent event) {
Although, it isn't entirely clear why you need that number. Your DataCompiler.Data method just prints the number passed into it, and that variable seemingly comes from nowhere in your code because it is not passed to the ActionListener.
* You should instead use Integer.parseInt(textInput.getText().trim()) inside Handler class / the listener code and not use a constructor. Otherwise, you'd always get the number value when you add the Handler, which would be an empty string and throw an error because the text area has no number in it.
Additionally, wc.miner(); returns a value, but calling it on its own without assigning it to a number just throws away that return value.

Make an Apple give you Experience?? | Minecraft Forge Modding 1.7.10

Hello people of the internet, I would like to know if there was a way to make a custom food item give you XP. I am in the middle of making a mod and would like "SimonApple" To give me XP. Please let me know if there is a way to do this.
package com.notsimon.blocksplus;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
#Mod(modid = "ep", name = "Experience Plus", version = "1.0")
public class ExperiencePlus {
public static Item SimonApple;
public static Item MagentaDust;
public static Block MagentaOre;
public static Block MagentaBlock;
#EventHandler
public void preInit(FMLPreInitializationEvent event) {
//Item/Block init and registering
//Config handling
//X * 0.5 = 20 Hunger
SimonApple = new ItemFood(10, 0.5F, false).setUnlocalizedName("SimonApple").setTextureName("bp:SimonApple").setCreativeTab(tabBlocksPlus);
MagentaOre = new BlockTable(Material.iron).setBlockName("MagentaOre").setBlockTextureName("bp:MagentaOre").setCreativeTab(tabBlocksPlus);
MagentaDust = new ItemTable().setUnlocalizedName("MagentaDust").setTextureName("bp:MagentaDust").setCreativeTab(tabBlocksPlus);
MagentaBlock = new MagentaBlock(Material.iron).setBlockName("MagentaBlock").setBlockTextureName("bp:MagentaBlock").setCreativeTab(tabBlocksPlus);
//item.itemTable and substring(5) removes "item."
GameRegistry.registerItem(SimonApple, SimonApple.getUnlocalizedName().substring(5));
GameRegistry.registerBlock(MagentaOre, MagentaOre.getUnlocalizedName().substring(5));
GameRegistry.registerItem(MagentaDust, MagentaDust.getUnlocalizedName().substring(5));
GameRegistry.registerBlock(MagentaBlock, MagentaBlock.getUnlocalizedName().substring(5));
GameRegistry.registerWorldGenerator(new OreGeneration(), 0);
}
#EventHandler
public void init(FMLInitializationEvent event) {
//Proxy, TileEntity, entity, GUI and Packet Registering
GameRegistry.addRecipe(new ItemStack(SimonApple, 2), new Object[]{"MMM","MBM","MMM", 'M', ExperiencePlus.MagentaDust, 'B', ExperiencePlus.MagentaBlock});
GameRegistry.addRecipe(new ItemStack(MagentaBlock), new Object[] {"MMM", "MMM", "MMM",'M', ExperiencePlus.MagentaDust});
}
#EventHandler
public void postInit(FMLPostInitializationEvent event) {
}
public static CreativeTabs tabBlocksPlus = new CreativeTabs("tabBlocksPlus"){
#Override
public Item getTabIconItem() {
return new ItemStack(MagentaOre).getItem();
}
};
}
You can't edit the current apple item in the game, you would have to create your own one as a forge mod item, which seems like what oyu have done. To make an item give XP, you use this:
player.addExperienceLevel(1); //player is an EntityPlayer or an EntityPlayerMP
SimonApple Item Class
This is what the item class for the SimonApple would look like (without imports):
public class SimonApple extends ItemFood {
private static final int LevelsToAdd = 10; //just an example number; play around with it
public SimonApple(String unlocalizedName, int healAmount, float saturationModifier, boolean wolvesFavorite, CreativeTab creativeTab) {
super(healAmount, saturationModifier, wolvesFavorite);
this.setUnlocalizedName(unlocalizedName);
this.setTextureName(Main.MODID + ":" + unlocalizedName);
this.setCreativeTab(creativeTab);
}
#Override
protected void onFoodEaten(ItemStack stack, World world, EntityPlayer player) {
super.onFoodEaten(stack, world, player);
player.addExperienceLevel(LevelsToAdd);
}
}
Changing Variables in the ExperiencePlus Class
You would need to change this:
public static Item SimonApple;
To something around the lines of this:
public static Item simonApple;
And you would need to change this:
SimonApple = new ItemFood(10, 0.5F, false).setUnlocalizedName("SimonApple").setTextureName("bp:SimonApple").setCreativeTab(tabBlocksPlus);
To just this:
simonApple = new SimonApple("SimonApple", 10, .5f, false, tabBlocksPlus);
NOTE: 10 should be the heal amount, and .5f should be the saturation amount (see table here)
Either create a new item as Abob78 suggests, or create an eventHandler that subscribes to the PlayerUseItem event to be triggered at the Finish state.
To limit the items that that trigger it, you'll have to look at using the itemstack NBT data to store a flag to identify "simon apples" from regular apples. this can be something as simple as a boolean flag such as "isSimonApple"
From the event, you should be able to extract an EntityLiving reference that can be cast to a player reference.
Then either augment the triggering player's XP or spawn XP orbs at their location.

Minecraft Bukkit: How can I access properties/methods in another class from the main class?

Hi everyone I'm trying to use variables from the Main class into my Event Listener class. This is a Minecraft Java Bukkit code that I'm working with. I'm trying to receive the "CanRestart" static boolean variable from my MainClass and trying to use it in the Event Listeners class. No errors popup in the program, but in the console there are errors and the plugin does not work.
I know that the problem is this line of code from the Event Listeners class (which I created to try and get the variables from the Main class):
MainProgram MainCode = new MainProgram();
I do not have that much knowledge with Java's OOP, but I was really wondering if I could get help.
I'm trying to get a code like this work:
MainProgram MainCode = new MainProgram();
if(MainCode.CanRestart == true){
//We received a variable from the main class!
}
Here is my Main Class:
package me.Shadowsych;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class MainProgram extends JavaPlugin{
public static boolean CanRestart = true;
public int CDNumber = 5;
public int DetermineCounter;
#Override
public void onEnable(){ //Essential, when your plugin is enabled.
getLogger().info("Shadowsych's Command Plugin is working!"); //CMD will print this out.
new EventListeners(this); //Inherits the EventListeners class
}
#Override
public void onDisable(){//Essential, when your plugin is disabled.
}
#SuppressWarnings("deprecation")
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { //Creates command function.
Player player = (Player) sender;
if(cmd.getName().equalsIgnoreCase("timer")){
if(CanRestart == true){ //Checks to see if the Timer is still running
CanRestart = false; //The timer has ran.
CDNumber = 5;
DetermineCounter = Bukkit.getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Runnable(){
public void run(){
if(CDNumber > -1){ //This can be a 0 integer
if(!(CDNumber == 0)){ //If once it is 0.
player.sendMessage("" + CDNumber); //The "" is used to make number a String.
}
CDNumber --; //Makes the number -1 if it's already a 0.
}
if(CDNumber == -1){ //Now catches that the number is -1.
player.sendMessage("Count down finished");
Bukkit.getServer().getScheduler().cancelTask(DetermineCounter); //Disables counter.
CanRestart = true; //You can restart your timer now.
return;
}
}
}, 0L, 20L);
}
}
return false; //Is essential in a boolean function.
}
}
Here is my Event Listener Class:
package me.Shadowsych;
import me.Shadowsych.MainProgram;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerToggleFlightEvent;
public class EventListeners implements Listener {
MainProgram MainCode = new MainProgram();
public EventListeners(MainProgram plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin); //Registers Event Main
}
#EventHandler
public void PlayerToggleFlight(PlayerToggleFlightEvent EventFloat){
Player player = EventFloat.getPlayer();
if(player.getGameMode() == GameMode.CREATIVE)
return; //If the player is creative then don't do this Event.
EventFloat.setCancelled(true);
player.setAllowFlight(false);
player.setVelocity(player.getLocation().getDirection().multiply(0).setY(1));
player.sendMessage(ChatColor.AQUA + "You have double jumped!");
}
#EventHandler
public void PlayerJump(PlayerMoveEvent EventJumped){
Player player = EventJumped.getPlayer();
if((player.getGameMode() != GameMode.CREATIVE) //Player is not creative
&& (player.getLocation().subtract(0, 1, 0).getBlock().getType() != Material.AIR) //Block beneath them is not air
&& (!player.isFlying())) //Player is not flying
{
player.setAllowFlight(true); //Allow the player to fly
}
}
}
Here is what the console says:
http://prntscr.com/9ki7a5
In your listener class, you take the MainProgram object passed in through the constructer and create an reference variable for it in. This way you can access your MainProgram class in your listeners class.
EventListeners class:
//Change
MainProgram MainCode = new MainProgram();
//to
MainProgram MainCode;
public EventListeners(MainProgram plugin) {
//Add this
this.MainCode = plugin;
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
Also remove the static modifier from CanRestart.
You're creating another instance of your plugin's main class with new MainProgram(), which is not necessary in order to access variables in the original instance of the main class created when the plugin is first loaded, especially if the variables you are trying to access are static and thus don't belong to only a specific object. Since the CanRestart boolean is public and static, you can use just MainProgram.CanRestart to access that boolean. If the variable were however not static and therefore an "instance variable" (where each object has their own copy of a variable), then you'd need to add a reference to the original main class (not a new instance) in the listener so you could access variables/methods from the main class in the listener class.

Lwjgl 3, How to get OpenGL context current in the current thread?

I am using OpenGL in LWJGL 3 and I get the following error;
Exception in thread "main" java.lang.IllegalStateException: There is no OpenGL context current in the current thread.
at org.lwjgl.opengl.GL.getCapabilities(GL.java:157)
at org.lwjgl.opengl.GL11.getInstance(GL11.java:1390)
at org.lwjgl.opengl.GL11.glClearColor(GL11.java:1842)
at com.base.engine.RenderUtil.initGraphics(RenderUtil.java:13)
at com.base.engine.Main.<init>(Main.java:14)
at com.base.engine.Main.main(Main.java:24)
This is the RenderUtil class where initGraphics is called from the constructor of my main class. I have also tried to call initGraphics after creating a window with GLFW which has also generated a similar error message.
package com.base.engine;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL30.*;
public class RenderUtil {
public static void clearScreen() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
public static void initGraphics() {
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glFrontFace(GL_CW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glEnable(GL_FRAMEBUFFER_SRGB);
}
}
Also, I am not using multithreading. To create a window I call the method Window.createWindow(1366, 768, "Test"); from my main method.
```
private static Long window;
public static String createWindow(int width, int height, String title) {
if (GLFW.glfwInit() == 0) {
return "GLFW failed to initialise.";
}
GLFW.glfwWindowHint(GLFW.GLFW_SAMPLES, 4);
window = GLFW.glfwCreateWindow(width, height, title,
GLFW.glfwGetPrimaryMonitor(), 0);
if (window == null) {
GLFW.glfwTerminate();
return "Failed to create window.";
}
GLFW.glfwMakeContextCurrent(window);
return "GLFW has established a window.";
}
I have tried putting `RenderUtil.initGraphics();` two different position in my main method, both resulting in errors.
private boolean isRunning = false;
private Game game;
// This is the constructor
public Main() {
// Pos 1 - RenderUtil.initGraphics();
isRunning = false;
game = new Game();
}
public static void main(String[] args) {
System.out.println(Window.createWindow(1366, 768, "Test"));
// Pos 2 - RenderUtil.initGraphics();
Main game = new Main();
game.start();
}
Add a call to GLContext.createFromCurrent() at the end of the createWindow method.
This method is needed to set the context used by the LWJGL GL** classes under the hood.
EDIT:
Since the latest nightly (3.0.0b #11) this no longer works, as the GLContext class no more exists. Instead, add GL.createCapabilities() at the end of the createWindow method.
I know that this thread is 4 years old but if someone of you still needs a solution here you go:
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
public class Main {
private static long window = 0;
public static void main(String[] args) {
if(!GLFW.glfwInit()) {
throw new RuntimeException("Cannot initialize OPenGL");
}
window = GLFW.glfwCreateWindow(1024, 764, "Ya yeet", 0, 0);
if(0 == window) {
GLFW.glfwTerminate();
throw new RuntimeException("Cannot create window");
}
GLFW.glfwMakeContextCurrent(window);
GL.createCapabilities();
String glVersion = GL11.glGetString(GL11.GL_VERSION);
System.out.println(glVersion);
}
}
To init and use LWJGL 3 you need to do next (code in Kotlin):
import org.lwjgl.glfw.GLFW
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL11
import org.lwjgl.system.MemoryUtil.NULL
class VersionInfo {
var window: Long = NULL
fun run() {
initGl()
// use openGL
val glVersion = GL11.glGetString(GL11.GL_VERSION)
println("GL version: $glVersion")
}
private fun initGl() {
// check GLFW
if (!GLFW.glfwInit()) {
throw IllegalStateException("Can not initialize GLFW")
}
// create window
window = GLFW.glfwCreateWindow(1024, 764, "glfw", NULL, NULL)
// check window
if (NULL == window) {
GLFW.glfwTerminate()
throw IllegalStateException("Can not create new GLFW window")
}
// make GL context in the current thread
GLFW.glfwMakeContextCurrent(window)
// create capabilities
GL.createCapabilities()
}
companion object {
#JvmStatic
fun main(args: Array<String>) {
VersionInfo().run()
}
}
}
For more information, please, see official get-started guide: http://www.lwjgl.org/guide
Or Wiki: https://github.com/LWJGL/lwjgl3-wiki/wiki

Categories