NullPointerException when attempting to save webcam image from Java Applet [duplicate] - java

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
NullPointerException when try to capture imagem from webcam
I saw this good webcam applet but i'm beginner with java, and I'm trying just put another JButton called Capture that will take a picture through the webcam and save in a specific path.
CODE OF MY CAPTURE BUTTON
startC.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
// Grab a frame
FrameGrabbingControl fgc = new FrameGrabbingControl() {
#Override
public Component getControlComponent() {
// TODO Auto-generated method stub
return null;
}
#Override
public Buffer grabFrame() {
// TODO Auto-generated method stub
return null;
}
};
player.getControl("javax.media.control.FrameGrabbingControl");
buf = fgc.grabFrame();
// Convert it to an image
BufferToImage btoi = new BufferToImage((VideoFormat)buf.getFormat());
img = btoi.createImage(buf);
// show the image
//imgpanel.setImage(img);
// save image
try {
saveJPG(img,"c:\\test.jpg");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
SAVE JPG METHOD
public static void saveJPG(Image img, String s) throws IOException
{
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
File outputfile = new File("C:\\saved.jpg");
ImageIO.write(bi, "png", outputfile);
}
ERROR
Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at com.colorfulwolf.webcamapplet.WebcamApplet$6.actionPerformed(WebcamApplet.java:524)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
In my line 524 I have the code
BufferToImage btoi = new BufferToImage((VideoFormat)buf.getFormat());
FGC declaration
FrameGrabbingControl fgc = new FrameGrabbingControl() {
#Override
public Component getControlComponent() {
// TODO Auto-generated method stub
return null;
}
#Override
public Buffer grabFrame() {
// TODO Auto-generated method stub
return null;
}
};

Your application is throw a NullPointerException because you try to invoke a method on a null object, buf.
Even though you declare buf = fgc.grabFrame();, your buf object is null because fgc.grabFrame() is returning null.
#Override
public Buffer grabFrame() {
// TODO Auto-generated method stub
return null;
}
To fix the issue, you can return new Buffer() instead of null in your fgc.grabFrame() implementation.

Related

errors when replace phantomjs to headless chromedriver

i got many errors about js... so i changed to chromedriver headless, and it work better for screenshot a specific element, but i got an errors in a other screenshot(s) code
Starting ChromeDriver 2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387)
on port 44903
Only local connections are allowed.
janv. 31, 2019 7:02:22 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFOS: Detected dialect: OSS
Exception in thread "AWT-EventQueue-0" java.awt.image.RasterFormatException: (y + height) is outside of Raster
at sun.awt.image.ByteInterleavedRaster.createWritableChild(Unknown Source)
at java.awt.image.BufferedImage.getSubimage(Unknown Source)
at CarteEtdInfo.photoProfile(CarteEtdInfo.java:57)
at Accueil.<init>(Accueil.java:99)
at Login$2.actionPerformed(Login.java:287)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicRootPaneUI$Actions.actionPerformed(Unknown Source)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.KeyboardManager.fireBinding(Unknown Source)
at javax.swing.KeyboardManager.fireKeyboardAction(Unknown Source)
at javax.swing.JComponent.processKeyBindingsForAllComponents(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
this is the the code that have errors from class CarteEtdInfo
public void photoProfile() throws IOException {
String cookie = String.join("\n",Files.readAllLines(Paths.get("temp\\cookie.txt")));
Login webpage = new Login();
WebDriver pagee = webpage.driver;
pagee.get("https://www4.inscription.tn/ORegMx/servlet/AuthentificationEtud?Idsession="+cookie+"&action1=toCarteEtd");
// Get entire page screenshot
WebElement taswira = driver.findElement(By.xpath("/html[1]/body[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/table[2]/tbody[1]/tr[4]/td[1]/div[2]/div[1]/table[2]/tbody[1]/tr[2]/td[1]/img[1]"));
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = null;
try {
fullImg = ImageIO.read(screenshot);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the location of element on the page
org.openqa.selenium.Point point = taswira.getLocation();
// Get width and height of the element
int eleWidth = taswira.getSize().getWidth();
int eleHeight = taswira.getSize().getHeight();
// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight); // line 57
try {
ImageIO.write(eleScreenshot, "png", screenshot);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Copy the element screenshot to disk
File screenshotLocation = new File("temp\\avatar.png");
try {
FileUtils.copyFile(screenshot, screenshotLocation);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this is the line 57
BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
the preivious code of screenshot an element in Login class works fine, so why this one have a problem ?
also the chromedriver not headless works fine but the headless not
Headless chrome default window size might be smaller than expected and this might cause your element to be outside of the window, hence not visible. You can either set the widndow size yourself or maximize window by using:
chromeOptions.addArguments(""--start-maximized")
i fixed the problem by adding
chromeOptions.addArguments("window-size=1980,960");

Unhandled Exception Type Java

I am using Sikuli with Java to create a small automation tool. I am having trouble with this Unhandled Exception error. I am trying to pass a method I created to the GUI actionPerformed method.
package mission;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
import tools.ChooseMission;
public class Story {
public static void runStoryMissions(int chapter, int stage) throws FindFailed, InterruptedException {
Screen screen = new Screen();
ChooseMission.ChooseChapter(screen,chapter);
ChooseMission.ChooseStage(screen, stage);
int dailyBiometricCount = ChooseMission.dailyBiometricCount(screen);
Pattern start = new Pattern("img/chapters/start.png");
Pattern replay = new Pattern("img/chapters/replay.png");
Pattern next = new Pattern("img/chapters/next.png");
Pattern mission_finish_bar = new Pattern("img/chapters/mission_finish_bar.png");
screen.click(start);
System.out.println("The mission has started.");
Thread.sleep(2000);
while (find(screen, mission_finish_bar) == false) {
System.out.println("Still playing the mission...");
}
if (screen.exists(mission_finish_bar) != null){
System.out.println("The mission has finished.");
}
System.out.println("Wait for 5 Seconds");
Thread.sleep(5000);
System.out.println("Click repeat button");
screen.click(replay);
}
Here is the code for my actionPerformed listener button:
btnStartMissions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int chapter = Integer.parseInt(txtFldChapter.getText());
int stage = Integer.parseInt(txtFldStage.getText());
System.out.println("Chapter #: " + chapter);
System.out.println("Stage #: " + stage);
try {
Story.runStoryMissions(chapter, stage);
} catch (FindFailed e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
There is a error at Story. runStoryMissions(chapter,stage) it says: Unhandled Exception type FindFailed and InterruptedException
Stack Trace:
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
at mission.Story.runStoryMissions(Story.java:12)
at GuiFrame1$2.actionPerformed(GuiFrame1.java:94)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.IllegalThreadStateException: Cannot call method from the event dispatcher thread
at java.awt.Robot.checkNotDispatchThread(Unknown Source)
at java.awt.Robot.waitForIdle(Unknown Source)
at org.sikuli.script.Mouse.move(Mouse.java:345)
at org.sikuli.script.Mouse.move(Mouse.java:318)
at org.sikuli.script.Mouse.init(Mouse.java:59)
at org.sikuli.script.Screen.initScreens(Screen.java:89)
at org.sikuli.script.Screen.<clinit>(Screen.java:58)
... 38 more
Okay, I found the answer to my problem if anyone is interested.
Sikuli uses the java.awt features so scripts cannot implement and use Swing elements.
Java AWT Robot actions cannot be called froma Java swing container.
Solution is to create a new Thread:
new Thread(() -> {
try {
Story.runStoryMissions(chapter, stage);
} catch (FindFailed | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}).start();

Serialize and Saving an ArrayList of double [] in Java

I want to serialize and save an arraylist that contains a double [] arraylist in java. Here is my code.
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
FileInputStream fileInputStream = null;
ObjectInputStream objectInputStream = null;
public void writeArrayListToFile(ArrayList<ArrayList<double []>> arraylist, String outputFilePath){
System.out.println("Start saving the file at : " + outputFilePath);
try {
fileOutputStream = new FileOutputStream(outputFilePath , true);
objectOutputStream = new ObjectOutputStream(objectOutputStream);
objectOutputStream.writeObject(arraylist);
System.out.println("Arraylist Saved Successfully...");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But I get an error and following is the stack trace.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(Unknown Source)
at java.io.ObjectOutputStream.(Unknown Source)
at com.fyp.imur2.SaveArrayListToFile.writeArrayListToFile(SaveArrayListToFile.java:24)
at com.fyp.imur2.JPanelJFreeChart.btnSaveGestureCollectionActionPerformed(JPanelJFreeChart.java:380)
at com.fyp.imur2.JPanelJFreeChart.access$5(JPanelJFreeChart.java:375)
at com.fyp.imur2.JPanelJFreeChart$6.actionPerformed(JPanelJFreeChart.java:166)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Can someone help me to solve this issue? Any help would be appreciated. Thanks in advance.
Need to pass fileOutputStream while constructing the instance of ObjectOutputStream
objectOutputStream = new ObjectOutputStream(fileOutputStream);
on the line
objectOutputStream = new ObjectOutputStream(objectOutputStream);
You try to call the constructor with the objectOutputStream object, which is null. Looks like you meant to call it with fileOutputStream, like this:
objectOutputStream = new ObjectOutputStream(fileOutputStream);

Trying to cast an Image to a BufferedImage

I'm writing java code for a game and when creating the health bars I saw an exception that confused me greatly. The code and stack is below:
Code:
package com.teamanubiz.pixelhero;
import java.awt.Graphics;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import com.teamanubiz.gameapi.gfx.Sprite;
public class GUIRenderLayer {
public void renderStatBar(GUIPosition pos, Graphics g, int health, int maxHealth, int mana, int maxMana) {
Sprite healthBar = null;
try {
healthBar = new Sprite(ImageIO.read(new File("res\\gui\\bar.png")));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
healthBar.crop(0, 0, 128, 32);
healthBar.scale(256, 32);
Sprite manaBar = null;
try {
manaBar = new Sprite(ImageIO.read(new File("res\\gui\\bar.png")));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
manaBar.crop(0, 32, 128, 32);
manaBar.scale(265, 16);
Sprite temp = null;
try {
temp = new Sprite(ImageIO.read(new File("res\\gui\\bar.png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
temp.crop(0, 64, 128, 32);
temp.scale(256, 32);
Sprite emptyHealth = new Sprite(temp.getCurrent());
temp.scale(256, 16);
Sprite emptyMana = new Sprite(temp.getCurrent());
if (pos == GUIPosition.BOTTOM) {
double percent_h = health / maxHealth;
double percent_m = mana / maxMana;
healthBar.crop(0, 0, (int) ((int) 256 * percent_h), 32);
manaBar.crop(0, 0, (int) ((int) 256 * percent_m), 16);
g.drawImage(emptyMana.getCurrent(), 100, 464, null);
g.drawImage(emptyHealth.getCurrent(), 100, 432, null);
g.drawImage(healthBar.getCurrent(), 100, 432, null);
g.drawImage(manaBar.getCurrent(), 100, 464, null);
}
}
}
This class is referencing a custom library containing the class Sprite. It for some reason says that I am trying to cast a ToolkitImage to a BufferedImage in the below method of Sprite.java.
public void crop(int xOffset, int yOffset, int width, int height) {
BufferedImage temp = (BufferedImage) source;
temp = temp.getSubimage(xOffset, yOffset, width, height);
source = temp;
}
The variable source is an instance of an Image that is a field in Sprite.java
The stack below claims I am creating a ToolkitImage despite the fact new ImageIcon("res\\gui\\bar.png").getImage() returns only an Image. I do not convert the Image to a ToolkitImage ever in the code. This makes it extremely confusing.
Stacktrace:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
at com.teamanubiz.gameapi.gfx.Sprite.crop(Sprite.java:48)
at com.teamanubiz.pixelhero.GUIRenderLayer.renderStatBar(GUIRenderLayer.java:55)
at com.teamanubiz.pixelhero.GameWindow.tick(GameWindow.java:14)
at com.teamanubiz.gameapi.Display.paint(Display.java:95)
at javax.swing.RepaintManager$4.run(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1300(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
at com.teamanubiz.gameapi.gfx.Sprite.crop(Sprite.java:48)
at com.teamanubiz.pixelhero.GUIRenderLayer.renderStatBar(GUIRenderLayer.java:55)
at com.teamanubiz.pixelhero.GameWindow.tick(GameWindow.java:14)
at com.teamanubiz.gameapi.Display.paint(Display.java:95)
at javax.swing.RepaintManager$4.run(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1300(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
at com.teamanubiz.gameapi.gfx.Sprite.crop(Sprite.java:48)
at com.teamanubiz.pixelhero.GUIRenderLayer.renderStatBar(GUIRenderLayer.java:55)
at com.teamanubiz.pixelhero.GameWindow.tick(GameWindow.java:14)
at com.teamanubiz.gameapi.Display.paint(Display.java:95)
at javax.swing.RepaintManager$4.run(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1300(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
BufferedImage is a type of Image, but Image is not a type BufferedImage, you could, for example, cast BufferedImage to an Image.
Instead of using ImageIcon to load the image, use ImageIO.read, which returns a BufferedImage
So instead of...
Sprite healthBar = new Sprite((Image)new ImageIcon("res\\gui\\bar.png").getImage()); // I Never Instatiated a ToolkitImage!!!!!!!!
Nb: ImageIcon delegates the actual loading of the image to Toolkit and wraps it in a Icon interface
Use something like...
Sprite healthBar = new Sprite(ImageIO.read(new File("res\\gui\\bar.png")));
No you don't "convert" the Image to a ToolKitImage, but that's what the JVM is giving you when you call new ImageIcon("res\\gui\\bar.png").getImage(), and not a BufferedImage. The ImageIcon API states that getImage() returns an object of Image type, but does not specify what type of Image. Since Image is an interface, you know that there must be some concrete type underlying the returned Image object. If you need a BufferedImage you could one, and draw this Image into it.
Myself, I wouldn't even use an ImageIcon here if I wanted a BufferedImage, but rather would use ImageIO.read(...) which returns a BufferedImage.
So....
BufferedImage img = ImageIO.read(getClass().getResourceAsStream("res/gui/bar.png"));
Sprite healthBar = new Sprite(img);

Can't fine the error with Operation not allowed after ResultSet closed

Method where im getting an error on:
public ArrayList<Log> selectAllLogs(){
if(openConn()){
ArrayList<Log> list = new ArrayList<Log>();
Boolean doesLogExists = false;
String query = "SELECT * FROM logs a LEFT JOIN log_lines s on a.log_id = s.log_id";
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
Log log = null;
while(rs.next()){
for (Log l : list) {
if(l.getLogId() == rs.getInt("log_id")){
log = l;
doesLogExists = true;
System.out.println("check");
}
}
if(doesLogExists){
log.getLogLines().add(rs.getString("log_lines"));
Iterator<Log> iter = list.iterator();
int i = 0;
System.out.println("true");
while(iter.hasNext()){
if(iter.next().getLogId() == ((list.get(i).getLogId()))){
list.remove(i);
list.add(i, log);
break;
}
i++;
}
doesLogExists = false;
} else {
System.out.println("false");
log = new Log();
log.setDateName(rs.getString("log_name"));
log.setLogId(rs.getInt("log_id"));
log.getLogLines().add(rs.getString("log_lines"));
list.add(log);
}
}
}
catch(SQLException sqle){
sqle.printStackTrace();
}
try {
closeConn();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
try {
closeConn();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Stackstrace:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:804)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:852)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5773)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5693)
at DataLayer.DatabaseConnector.selectAllLogs(DatabaseConnector.java:313)
at model.LogContainer.<init>(LogContainer.java:15)
at model.LogContainer.getInstance(LogContainer.java:20)
at view.LogOverview.initGui(LogOverview.java:91)
at view.LogOverview.<init>(LogOverview.java:27)
at controller.MainFrameController.actionPerformed(MainFrameController.java:65)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Im getting an error on this piece of code, it is out of the else part in the while loop.
list.add(log);
I have googled the exception but i don't understand it. Can someone help me?
You can see from the stacktrace that the statement where the exception occurs in the method selectAllLogs is actually the call to com.mysql.jdbc.ResultSetImpl.getString, and not the statement list.add(log); There's an off by one error in where you thought the exception was occuring.
The reason that you're getting the SQLException is probably because you're not closing the ResultSet. This question is about the same issue.

Categories