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

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

Related

Cannot spawn falling blocks in minecraft

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().

Selenium/Java: can I separate a Drag and Drop action in two actions belonging to two separate classes?

I'm aware this is kind of a weird thing to want to do, but right now I'm building a test project, and I separated the several areas/containers of the application I'm testing in different classes, as a measure to keep organization. Therefore, if I want to drag an element from area A to area B, I've got to separate my D&D action in 2 methods, each belonging to a different class. I tried doing that in two ways:
Way 1:
//Class A
public void dragThumbnail(int startPosition) {
Actions act = new Actions($(By.cssSelector("body")).getWrappedDriver());
act.clickAndHold(getThumbnailFromPosition(startPosition)).build().perform();
}
//Class B
public void dropInDivider(int endPosition) {
Actions act = new Actions($("body").getWrappedDriver());
act.moveToElement(getDividerFromPosition().get(endPosition)).release().perform();
}
Way 2:
//Class A:
public void dragThumbnail(int startPosition) throws AWTException {
Robot robot = new Robot();
int x = (getThumbnailFromPosition(startPosition)).getLocation().getX();
int y = (getThumbnailFromPosition(startPosition)).getLocation().getY();
robot.mouseMove(x,y);
robot.mousePress(InputEvent.BUTTON1_MASK);
}
//Class B
public void dropInDivider(int endposition) throws AWTException {
Robot robot = new Robot();
int x = getDividerFromPosition().get(endposition-1).getLocation().getX();
int y = getDividerFromPosition().get(endposition-1).getLocation().getY();
robot.mouseMove(x, y);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
Evidently, none of them worked, because otherwise I wouldn't be here. I'm not too knowledgeable about Selenium Java yet, is anything wrong with my code, or is this just impossible/unfeasible to do, and I've just got to have everything in the same class?
I appreciate each and every input I might get.
This can be achieved using a Mouse class which has a singleton initialization based on the driver. This means that each instance of WebDriver will return the same mouse object.
import java.util.HashMap;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.interactions.Actions;
public class Mouse {
private Actions actions;
private WebDriver driver;
protected Mouse(WebDriver driver) {
this.driver = driver;
actions = new Actions(driver);
}
private static HashMap<WebDriver, Mouse> mice = new HashMap<>();
public static Mouse getMouse(WebDriver driver) {
Mouse mouse = mice.get(driver);
if (mouse == null) {
mouse = new Mouse(driver);
mice.put(driver, mouse);
}
return mouse;
}
public void clearActions() {
actions = new Actions(driver);
}
public Actions addAction() {
return actions;
}
public void perform() {
actions.build().perform();
}
}
Use this mouse object to add operation in each class. Note here that we are not building or performing the operation here. We are adding the operation to the Actions class. Then in the execution flow class we will perform the operations as a sequence.
public class A {
public void dragThumbnail(int startPosition) {
Mouse.getMouse(driver).addAction().clickAndHold(getThumbnailFromPosition(startPosition));
}
}
public class B {
public void dropInDivider(int endPosition) {
Mouse.getMouse(driver).addAction().moveToElement(getDividerFromPosition().get(endPosition));
}
}
Then call the below sequence to get the operation executed as a whole in
public class Test {
public void executeTest() {
// Get the mouse
Mouse mouse = Mouse.getMouse(driver);
// Clear previous mouse operations saved (if any)
mouse.clearActions();
// Add the operation in class A
a.dragThumbnail(startPosition);
// Add the operation in class B
b.dropInDivider(endPosition);
// Perform the operation now
mouse.perform();
}
}
I solved this issue as follows:
Step 1: Create a method to move the mouse cursor to points (x1, y1):
private void mouseMove(int destinationLocationX, int destinationLocationY) throws AWTException {
Robot robot = new Robot();
Point mousePosition;
robot.mouseMove(destinationLocationX/2, destinationLocationY/2);
mousePosition = MouseInfo.getPointerInfo().getLocation();
while (mousePosition.x != destinationLocationX && mousePosition.y != destinationLocationY) {
mousePosition = MouseInfo.getPointerInfo().getLocation();
robot.mouseMove(destinationLocationX, destinationLocationY);
}
}
Then, I created methods to find the exact center of each element:
private int getElementX(SelenideElement element) {
return element.getLocation().x + element.getSize().getWidth()/2; }
private int getElementY(SelenideElement element) {
return element.getLocation().y + element.getSize().getHeight()/2; }
Then, I created a generic drag and drop method, that I then used in several different other methods:
private void dndToCenterOfObject(SelenideElement source, SelenideElement target)
throws AWTException {
Robot robot = new Robot();
robot.setAutoDelay(150);
int sourceX = getElementX(source);
int sourceY = getElementY(source);
int targetX = getElementX(target);
int targetY = getElementY(target);
mouseMove(sourceX, sourceY);
robot.mousePress(InputEvent.BUTTON1_MASK);
mouseMove(targetX, targetY);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
Hope this helps.

Event listener/ Scanner in Gridworld

I'm trying to control Bugs in GridWorld. I have tried two ways of doing this, neither of which have actually moved or turned the bug. They both compile but nothing happens.
Here is the Bug that will be controlled:
package info.gridworld.actor;
import info.gridworld.grid.*;
import info.gridworld.grid.Location;
import java.awt.Color;
public class MazeBug extends Bug {
public MazeBug() {
super(Color.blue);
}
public void forward(){
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
public void turnRight(){
setDirection(getDirection() + Location.RIGHT);
}
public void turnLeft(){
setDirection(getDirection() + Location.LEFT);
}
}
Here is the first way that I tried controlling the bugs with the keys W,A, and D using Scanner (not sure if I used scanner correctly)
package info.gridworld.actor;
import java.util.Scanner;
import info.gridworld.grid.*;
public class KeyTests extends Actor
{
public static ActorWorld world = new ActorWorld(new BoundedGrid<Actor>(20, 20));
public static MazeBug currentBug;
public static void main(String[] args) {
world.show();
world.add(new Location(1,11),new MazeBug());
while(true){
Scanner k = new Scanner(System.in);
String buttonpress = k.nextLine();
if (buttonpress.equals("w"))
currentBug.forward();
if (buttonpress.equals("d"))
currentBug.turnRight();
if (buttonpress.equals("a"))
currentBug.turnLeft();
}
}
}
Here is the 2nd way I tried to control the bug
package info.gridworld.actor;
import info.gridworld.grid.*;
public class KeyTests extends Actor
{
public static ActorWorld world = new ActorWorld(new BoundedGrid<Actor>(20, 20));
public static MazeBug currentBug;
public static void main(String[] args) {
world.add(new Location(1,11),new MazeBug());
java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new java.awt.KeyEventDispatcher() {
public boolean dispatchKeyEvent(java.awt.event.KeyEvent event) {
String key = javax.swing.KeyStroke.getKeyStrokeForEvent(event).toString();
if (key.equals("w"))
currentBug.forward();
if (key.equals("d"))
currentBug.turnRight();
if (key.equals("a"))
currentBug.turnLeft();
world.show();
return true;
}
});
world.show();
}
}
Thanks for any help in advanced
I am almost positive that your problem is that you put your controlling code in the Runner instead of your Bug's act method.
When GridWorld steps all it does is call each Actor's act method, so if your Actor has an unpopulated method it will just call the parent, or do nothing. Your runner, since it is not an 'Actor' has no act method, and after the first run is never looked at again.
Try this in your MazeBug:
public void act()
{
java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new java.awt.KeyEventDispatcher() {
public boolean dispatchKeyEvent(java.awt.event.KeyEvent event) {
String key = javax.swing.KeyStroke.getKeyStrokeForEvent(event).toString();
if (key.equals("w"))
forward();
if (key.equals("d"))
turnRight();
if (key.equals("a"))
turnLeft();
return true;
}
});
}
Note: I have never used EventListeners so can't help with that code.

How to avoid deprecation warnings for GWT HorizontalSplitPanel in NetBeans Java project?

Is it possible to avoid deprecation warning while compiling code with utility methods like:
public static void doSthForHorizontalSplitPanel(HorizontalSplitPanel hsp) {...}
and explicit declaration and/or creation of HorizontalSplitPanel widget, e.g.:
protected HorizontalSplitPanel main;
...
main = new HorizontalSplitPanel();
My goal is to eliminate these warnings without removing HorizontalSplitPanel usage, not giving global compiler flag (-Xlint:-deprecation) and with aid of minimal manual refactoring in terms of possible impact on code using HorizontalSplitPanel and my utility methods (i.e. as little code changes as possible).
Annotation #SuppressWarnings("deprecation") at method or class level seems not to work because of import HorizontalSplitPanel statements, replacement of deprecated HorizontalSplitPanel class in not an option (for now).
Is my goal possible to achieve at all? If so, what would be the best approach?
I'm using NetBeans 7.1, Java 1.6, GWT 2.3.
Standards mode and SplitlayoutPanel works better than the deprecated HorizontalSplitPanel.
Try this code you have to replace with HorizontalSplitPanel with HorizontalSplitLayoutPanel.
This code actually uses latest SplitLayoutPanel and the methods are equivalent to Deprecated HorizontalSplitPanel. The advantage is you don't have to change the code. Also pasted code for VerticalSplitPanel alternative VerticalSplitLayoutPanel. VerticalSplitLayoutPanel is unit tested and works fine.
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* author: MKK
* Date: 4/29/13
* Time: 10:41 AM
* /**
*
* GWT depecrated HorizontalSplitpanel as of version 2.0.
* This is a wrapper class which extends new SplitLayoutPanel and has all the methods of deprecated old Splitpanels for
* seamless integration with existing code without breaking.
* Replacement of old HorizontalSplitLayoutPanel with new SplitLayoutPanel
*
*
*/
public class HorizontalSplitLayoutPanel extends SplitLayoutPanel{
private ScrollPanel leftScrollPanel = new ScrollPanel();
private ScrollPanel rightScrollPanel = new ScrollPanel();
private Widget leftWidget;
private Widget rightWidget;
public HorizontalSplitLayoutPanel(){
super();
init();
}
boolean dragged;
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
dragged = true;
break;
case Event.ONMOUSEUP:
dragged = false;
break;
case Event.ONMOUSEMOVE:
break;
}
}
public boolean isResizing(){
return dragged;
}
private void init() {
setSize("100%", "100%");
addWest(leftScrollPanel, 300);
add(rightScrollPanel);
sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP );
}
public HorizontalSplitLayoutPanel(int splitterSize) {
super(splitterSize);
init();
}
public void setLeftWidget(Widget widget){
this.leftWidget = widget;
leftScrollPanel.clear();
leftScrollPanel.add(widget);
setSplitPosition("30%");
setWidgetToggleDisplayAllowed(leftScrollPanel,true);
}
public void setRightWidget(Widget widget){
try {
this.rightWidget = widget;
rightScrollPanel.clear();
rightScrollPanel.add(widget);
setSplitPosition("30%");
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public void removeWidget(Widget widget){
try {
if( leftScrollPanel.getWidget()== widget){
leftScrollPanel.remove(widget);
return;
}
rightScrollPanel.remove(widget);
} catch (Exception e) {
}
}
public void setSplitPosition(String percent){
if( percent.toLowerCase().indexOf("px") > -1){
percent = percent.replace("px","").trim();
int p = Integer.parseInt(percent);
setSplitPosition(p);
return;
}
percent = percent.replace("%","").trim();
int p = Integer.parseInt(percent);
double size = (getOffsetWidth()*p)/100.0;
if( p < 1.0 ){
size = 600;
}
setWidgetSize(leftScrollPanel, size);
}
public void setSplitPosition(int pixels){
setWidgetSize(leftScrollPanel, pixels);
}
public void hideLeftWidget() {
leftScrollPanel.clear();
setWidgetMinSize(leftScrollPanel,0);
}
public void showLeftWidget(){
leftScrollPanel.add(leftWidget);
}
public void hideRightWidget() {
rightScrollPanel.clear();
setWidgetMinSize(rightScrollPanel,0);
}
public void showRightWidget(){
rightScrollPanel.add(rightWidget);
}
}
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
/**
*
* GWT depecrated VerticalSplitPanel as of version 2.0.
* This is a wrapper class which extends new SplitLayoutPanel and has all the methods of deprecated old Splitpanels for
* seamless integration with existing code without breaking.
* Replacement of old VerticalSplitPanel with new SplitLayoutPanel
*
*
*/
public class VerticalSplitLayoutPanel extends SplitLayoutPanel {
private Widget topWidget;
private Widget bottomWidget;
private int offset=100;
private ScrollPanel topScrollPanel = new ScrollPanel();
private ScrollPanel bottomScrollPanel = new ScrollPanel();
public VerticalSplitLayoutPanel() {
super();
init();
}
public VerticalSplitLayoutPanel(int splitterSize) {
super(splitterSize);
init();
}
private void init() {
setSize("100%", "100%");
//int clientH = Window.getClientHeight()-offset;
// double size = clientH * 50/100;
addNorth(topScrollPanel, getOffsetHeight()/2.0);
add(bottomScrollPanel);
sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP );
}
boolean dragged;
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
dragged = true;
break;
case Event.ONMOUSEUP:
dragged = false;
break;
case Event.ONMOUSEMOVE:
break;
}
}
public boolean isResizing(){
return dragged;
}
public void setTopWidget(Widget widget){
topScrollPanel.add(widget);
}
public void setBottomWidget(Widget widget){
bottomScrollPanel.add(widget);
}
public void removeWidget(Widget widget){
try {
if( topScrollPanel.getWidget()== widget){
topScrollPanel.remove(widget);
return;
}
bottomScrollPanel.remove(widget);
} catch (Exception e) {
}
}
public void setSplitPosition(String percent){
if( percent.toLowerCase().indexOf("px") > -1){
percent = percent.replace("px","").trim();
int p = Integer.parseInt(percent);
setSplitPosition(p);
return;
}
percent = percent.replace("%","").trim();
int p = Integer.parseInt(percent);
int oH = getOffsetHeight();
if( oH == 0 ){
oH = (Window.getClientHeight()-offset);
}
double h = (oH*p)/100.0;
setWidgetSize(topScrollPanel, h);
}
public void setSplitPosition(int pixels){
setWidgetSize(topScrollPanel, pixels);
}
public void setOffset(int size){
this.offset = size;
}
}
My approach is as follows.
Replace every usage of HorizontalSplitPanel with HorizontalSplitPanelWrapper defined below, then fix imports - this will eliminate import HorizontalSplitPanel and add import HorizontalSplitPanelWrapper. Done.
#SuppressWarnings("deprecation")
public class HorizontalSplitPanelWrapper implements IsWidget {
private Panel hsp = new com.google.gwt.user.client.ui.HorizontalSplitPanel();
public Widget asWidget() {
return hsp;
}
public com.google.gwt.user.client.Element getElement() {
return hsp.getElement();
}
public <H extends EventHandler> HandlerRegistration addHandler(final H handler, GwtEvent.Type<H> type) {
return hsp.addHandler(handler, type);
}
public boolean isResizing() {
return ((com.google.gwt.user.client.ui.HorizontalSplitPanel) hsp).isResizing();
}
public void setWidth(String width) {
hsp.setWidth(width);
}
public void setSplitPosition(String pos) {
((com.google.gwt.user.client.ui.HorizontalSplitPanel) hsp).setSplitPosition(pos);
}
public void add(IsWidget w) {
hsp.add(w);
}
}
Additional remarks.
My solution uses little trick with IsWidget interface from GWT - this minimizes code impact, because Widget can be substituted with implementation of IsWidget in most calls to GTW APIs.
Every method of HorizontalSplitPanel used in my code is now implemented by HorizontalSplitPanelWrapper and just delegated to internal HorizontalSplitPanel stored by hsp field.
There must be no declarations of fields and methods with HorizontalSplitPanel as type/param/result, as it will always yield deprecation warnings, regardless of #SuppressWarnings("deprecation"). Because of this, hsp field is declared as Panel.
If there are more methods of HorizontalSplitPanel used in rest of the code, there must be dummy delegator method in HorizontalSplitPanelWrapper for every one of them. Proper HorizontalSplitPanel object must be retrieved from field hsp with explicit cast in every such method.
That's it. No more deprecation warnings because of HorizontalSplitPanel, which still can be used.

LWJGL won't read keyboard input

I'm trying to use LWJGL to get whether a key is pressed. If the escape key is pressed, then the application quits. However, I can't get it to read any keyboard input, although Display.isCloseRequested() works fine.
I'm on RHEL using LWJGL 2.6 and Java 1.6.
for(;;) {
// check if we want to quit
if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
System.exit(0); // can't get this to happen!
}
if(Display.isCloseRequested()) {
System.exit(0);
}
/* timer code omitted */
render();
Display.update();
}
Edit: The exact same code works perfectly fine on my Windows box, with the same versions of lwjgl and JRE.
Maybe you can check if the Keyboard is Created with the isCreated function?
Other then that I'm not all that good in programming so I can't provide you with any other input.
try this
Keyboard.isCreated()
I may or may not be helpful/reviving a dead topic here, but for any rogue Googlers I give you this:
It's my Input class from my Zdeva Engine
Here you go, without having to download the entire 'engine'..
package LWJGL;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
public class Input
{
public static boolean[] mouseButtons = {false, false, false};
public static int[] mousePos = new int[Mouse.getButtonCount()];
public static int[] keysBound = {Keyboard.KEY_A, Keyboard.KEY_B};
/**
* Initializes the input system. Loads keyconfig.
*
*/
public static void init()
{
System.out.println("Initializing input system...");
//Eventually will check for OS, and adjust keys accordingly.
System.out.println("Input system initialized!");
}
/**
* Updates all mouse info, keys bound, and performs actions.
*/
public static void tick()
{
mouseButtons[0] = Mouse.isButtonDown(0);
mouseButtons[1] = Mouse.isButtonDown(1);
mousePos[0] = Mouse.getX();
mousePos[1] = Mouse.getY();
while(Keyboard.next())
{
if(Keyboard.getEventKeyState())
{
doAction(Keyboard.getEventKey(), false);
}
}
for(int key : keysBound)
{
if(Keyboard.isKeyDown(key))
{
doAction(key, true);
}
}
while(Mouse.next())
{
doAction(-1, false);
}
doAction(0, true);
}
/**
* Does the associated action for each key. Called automatically from tick.
* #param key The key to check & perform associated action
*/
public static void doAction(int key, boolean ifRepeat)
{
if(mouseButtons[0])
{
}
if(mouseButtons[1])
{
}
if(key == keysBound[0] & ifRepeat)
{
System.out.println("a");
}
if(key == keysBound[1] & !ifRepeat)
{
System.out.println("b");
}
}
}

Categories