My program seems to work quite well, but I keep getting "IllegalStateExceptions: RunnableQueue not started or has exited" from time to time, when I try to resize my component. I have set the documentState to ALWAYS_DYNAMIC and I have read that you are supposed to use the JSVGCanvas' UpdateManager and call invokelater(). I understand that it is available after the first time that
gvtBuildCompleted(GVTTreeBuilderEvent e)
is called, so I check whether it is running before I use it but I still get the exception.
The following method is called by a thread repeatedly and seems to cause the exception:
private void updateDomTree(final SVGComponent component, final Document doc)
{
if(component.getSvgCanvas().getUpdateManager() != null && component.getSvgCanvas().getUpdateManager().isRunning())
{
component.getSvgCanvas().getUpdateManager().getUpdateRunnableQueue().invokeLater(new Runnable()
{
public void run()
{
final Node newNode = doc.getChildNodes().item(0).getFirstChild();
//could be easier to get this value, but ... it works.
String newNodeId = newNode.getAttributes().getNamedItem("id").getFirstChild().getNodeValue();
NodeList nodes = component.getSvgDocument().getDocumentElement().getChildNodes();
Node updateNode = findElementById(nodes, newNodeId);
resizeComponent(component, doc);
component.getSvgCanvas().getSVGDocument().adoptNode(newNode);
component.getSvgCanvas().getSVGDocument().getDocumentElement().replaceChild(newNode, updateNode);
component.refreshSVGCanvas();
}
});
}
}
The actual resizing is done here:
protected void resizeComponent(SVGComponent component, Document doc)
{
Element svgRoot = doc.getDocumentElement();
final int svgWidth = Integer.parseInt(svgRoot.getAttribute("width"));
final int svgHeight = Integer.parseInt(svgRoot.getAttribute("height"));
String[] viewBox = svgRoot.getAttribute("viewBox").split(" ");
int viewBoxLeft = Integer.parseInt(viewBox[0]);
int viewBoxTop = Integer.parseInt(viewBox[1]);
final float factor = component.getScaleFactor();
String[] viewBoxOld = component.getSvgDocument().getDocumentElement().getAttribute("viewBox").split(" ");
int viewBoxLeftOld = Integer.parseInt(viewBoxOld[0]);
int viewBoxTopOld = Integer.parseInt(viewBoxOld[1]);
int xDiff = (int) ((viewBoxLeftOld - viewBoxLeft)*factor);
int yDiff = (int) ((viewBoxTopOld - viewBoxTop)*factor);
if ( viewBoxLeftOld != viewBoxLeft ) //If there is additional content left
{
component.setLocation(component.getLocation().x - xDiff, component.getLocation().y);
}
if ( viewBoxTopOld != viewBoxTop ) //If there is additional content right)
{
component.setLocation(component.getLocation().x, component.getLocation().y - yDiff);
}
component.getSvgDocument().getDocumentElement().setAttribute("width",""+svgWidth);
component.getSvgDocument().getDocumentElement().setAttribute("height",""+svgHeight);
component.getSvgDocument().getDocumentElement().setAttribute("viewBox", ""+viewBoxLeft+" "+viewBoxTop+" "+svgWidth+" "+svgHeight);
component.setSize((int)(svgWidth*factor),(int)(svgHeight*factor));
}
The method
refreshJSVGCanvas()
calls
JSVGCanvas.setDocument(Document);
JSVGCanvas.setSize(int, int);
Here's the full stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: RunnableQueue not started or has exited
at org.apache.batik.util.RunnableQueue.invokeLater(RunnableQueue.java:277)
at org.apache.batik.swing.svg.AbstractJSVGComponent.updateRenderingTransform(AbstractJSVGComponent.java:1057)
at org.apache.batik.swing.gvt.AbstractJGVTComponent$1.componentResized(AbstractJGVTComponent.java:237)
at java.awt.AWTEventMulticaster.componentResized(Unknown Source)
at java.awt.Component.processComponentEvent(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.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)
Thanks in advance, I have searched everywhere and tried a lot, but could not find a solution.
Edit:
This is the invokeLater-Method of Batik where the Exception is actually thrown:
public void invokeLater(Runnable r) {
if (runnableQueueThread == null) {
throw new IllegalStateException
("RunnableQueue not started or has exited");
}
synchronized (list) {
list.push(new Link(r));
list.notify();
}
}
runnableQueueThrad is set inside that class' run()-Method and set to null at the end.
So I guess I have to do some kind of synchronization.
Hazard a guess, the "public void run()" code should not be inside another method and really is a thread class/interface objects so called constructor(interface version actually).
Remove it to its own class(e.g. nested subclass to preserve scope) and implement the "thread runnable" interface on the class to place the "run()" method in it to use.
Stack trace says the run method is not available because it does not actually have such a method(or at least not properly declared) so it is in an "illegal state".
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I've been creating a Snakes program that contains an array of Segments. In this case, I believe that it is vital I use an array as the order matters. The first problem is that even after I create a "new Segment instance", it doesn't display any square (which is the first segment of the snake). But then, when I put a System.out.println() statement inside of the paint method (shown later), it throws a NullPointerException. Here is the code:
NOTE: the method increaseSegmentCount() was called once from an outside class. Also, this isn't the full code...
Snake
import java.awt.Graphics;
import java.awt.Point;
public class Snake implements Entity {
Point location;
Segment[] segments;
int segmentCount = 0;
public Snake(Point location) {
this.location = location;
segments = new Segment[25];
}
public void increaseSegmentCount() {
segments[segmentCount] = new Segment(new Point(location.x + (Segment.getSize().width * segments.length),
location.y + (Segment.getSize().height * segments.length)));
segmentCount++;
}
public Segment[] getSegments() {
return segments;
}
public int getSegmentCount() {
return segmentCount;
}
#Override
public void paint(Graphics g) {
for (Segment segment : segments) {
if (segment != null)
segment.paint(g);
}
}
}
paint() method after putting System.out.println statement in:
#Override
public void paint(Graphics g) {
for (Segment segment : segments) {
if (segment != null)
System.out.println("Called")
segment.paint(g);
}
}
Segment class (pretty straightforward class)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
public class Segment {
Point location;
public Segment(Point location) {
this.location = location;
}
public static Dimension getSize() {
return new Dimension(20, 20);
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(location.x, location.y, 20, 20);
}
}
paintComponent() method in View class (for debugging purposes)
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Entity entity : model.getEntities()) {
entity.paint(g);
}
}
And finally the error (after inserting the print statement... there is none before I inserted it):
Called
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Snake.paint(Snake.java:61)
at View.paintComponent(View.java:50)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
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$JavaSecurityAccessImpl.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$1200(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$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.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)
Any ideas? Also, please don't mark this as a duplicate and point me to another post that shows how to solve NPE's... I already know what to do and what's going on (for the most part), but this is a curious, thing I've come across and it's very confusing. Thanks.
you need { } for your if when you add the print statement...
if (segment != null) {
System.out.println("Called")
segment.paint(g);
}
You might consider using an automatic code formatter, which would make this obvious with the indentation.
I am new to Java programming. I am facing this error, and not understanding how to resolve this. Any help would be appreciated.
public class ThermostatView extends JFrame
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
ThermostatView frame = new ThermostatView();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Constructs a ThermostatView
*/
public ThermostatView()
{
thermostatObj = new Thermostat();
initComponents();
}
}
And this is my other class:
public class Thermostat extends ThermostatView
{
private static final long serialVersionUID = 1L;
public void setActualTempFunc(String actualTemp)
{
if(actualTemp.length() != 0)//actualTemp != null && !actualTemp.isEmpty())
lblActualTemp.setText(actualTemp);
else
lblActualTemp.setText("-");
}
}
the error is:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
JFrame cannot be resolved to a type
at Thermostat.<init>(Thermostat.java:3)
at ThermostatView.<init>(ThermostatView.java:145)
at ThermostatView$1.run(ThermostatView.java:128)
at java.awt.event.InvocationEvent.dispatch(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.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)
Looks like its getting caught in recursion.
Any help ???
I can see a few errors with your code.
You need to ensure you have all the required packages imported (e.g. java.awt.* etc).
Where are you delcaring lblActualTemp and thermostatObj ? You need to explicity delcare their type.
Using an IDE (development software) such as Eclipse, IntelliJ or Netbeans etc. usually spot these errors before you compile.
Running my program throws A Null Pointer Exception every time I create a new token of a specific type.
Here's the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Pattern.draw(Pattern.java:98)
at GameToken.draw(GameToken.java:68)
at GameTokenPanel.paintComponent(GameTokenPanel.java:83)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JLayeredPane.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
at java.awt.Container.paint(Unknown Source)
at java.awt.Window.paint(Unknown Source)
at javax.swing.RepaintManager$3.run(Unknown Source)
at javax.swing.RepaintManager$3.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$1100(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$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.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)
Here are the parts in the class which are affected by utoken0.draw(g2) and utoken1.draw(g2);
Here's my pattern class
public class Pattern
{
public static final int pattern0=0;
public static final int pattern1=1;
public static final int pattern2=2;
//private CrossPattern pattern1;
//private LineMid pattern3;
//private CircPattern pattern2;
private Rectangle bbox;
private int type;
private Random random = new Random();
private CrossPattern cross;
private CircPattern circ;
private LineMid linemid;
public Pattern(int type, Rectangle bbox)
{
this.bbox=bbox;
type=type;
if (type == 0)
{
cross= new CrossPattern(bbox);
}
if( type == 1)
{
circ=new CircPattern(bbox);
}
if(type ==2)
{
linemid=new LineMid(bbox);
}
}
public int getType()
{
return type;
}
public void draw(Graphics2D g2)
{
if(type==pattern0)
cross.draw(g2);
else if(type==pattern1)
circ.draw(g2);
else if (type==pattern2)
linemid.draw(g2);
}
}
Here is my GameToken Class:
public class GameToken implements VisibleShape
{
private boolean visible;
public Rectangle bbox;
private Pattern pattern;
private Color color;
Random random = new Random();
public GameToken(int patternType, int x, int y, int width, int height)
{
bbox = new Rectangle( x,y,width,height);
if(patternType==0)
{
pattern = new Pattern(patternType,bbox);
}
else if(patternType==1)
{
pattern= new Pattern(patternType,bbox);
}
else if(patternType==2)
{
pattern = new Pattern(patternType,bbox);
}
}
public void draw(Graphics2D g2)
{
g2.draw(bbox);
pattern.draw(g2);
}
}
Here is my panel:
public class GameTokenPanel extends JPanel {
private GameToken token1;
private final int TOKEN_WIDTH=35;
private Random random = new Random();
private ArrayList <GameToken> tokenarr;
private GameToken utoken0 = new GameToken(0, 0,0,TOKEN_WIDTH,TOKEN_WIDTH);
private GameToken utoken1 = new GameToken(1, 0,0,TOKEN_WIDTH,TOKEN_WIDTH);
private GameToken utoken2 = new GameToken(2, 0,0,TOKEN_WIDTH,TOKEN_WIDTH);
private GameToken currentToken= utoken0;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2= (Graphics2D) g;
g2.setColor(Color.BLUE);
utoken0.draw(g2);
utoken1.draw(g2);
//utoken2.draw(g2);
g2.setColor(Color.RED);
//token1.draw(g2);
for (int i =0; i<=10;i++)
{
tokenarr.get(i).draw(g2);
}
}
}
So basically, I use the panel to create the Game tokens which would create the Pattern and the rectangle. The Pattern class would then call the specific pattern class and draw it using the rectangle dimensions. Which would then appear on a frame.
The issue is that I would create utoken0 in the panel and draw it in the draw method. But when I would draw utoken1 the same way. It would lead to errors. I initiated them the same way and drew the same way . But I am getting error. Also , if I attempt to draw utoken2, it would also give me an error.
Also,when I generate the random tokens at the beginning of panel, It creates the 3 types. But when I would run the utoken and pick a specific type. Only the 0 pattern works, however 1 and 2 does not.
I don't have testing environment, simply dry run on your code.
Your code failure to set correct value into class variable type in Pattern. Hence, the type variable will have default value 0.
In draw method of Pattern class, it will call cross.draw(g2); since the type is 0. However, the code never initiate cross for pattern 1 or 2. It results in NullPointerException.
You should fix line in Pattern class from:
type=type;
to
this.type=type;
I have problems with idS. in sellContainer idS is 1 and in sellCtr is always 0 so the method addItemToSell is not working. Always give null pointer exception.
public class SellCtr{
private SellContainer sellContainer;
private OrderLineSell ols;
private int idS;
private int idOls;
public SellCtr(){
sellContainer = SellContainer.getInstance();
}
public void createSell(String date, Customer c, Employee e){
Sell sell = new Sell(date,c,e);
sellContainer.addSell(sell);
idS = sell.getId();
}
public void addItemToSell(OrderLineSell orderLineSell){
sellContainer.findSell(idS).addOrderLineSell(orderLineSell);
}
public int getId(){
return idS;
}
public int getIdOls(){
return idOls;
}
public Sell findSell(int idS){
return sellContainer.findSell(idS);
}
}
and the other class is :
public class SellContainer{
private ArrayList<Sell> sales;
private static int idS=0;
private static SellContainer instance=null;
public SellContainer(){
sales = new ArrayList<>();
}
public static SellContainer getInstance(){
if(instance == null){
instance = new SellContainer();
}
return instance;
}
public void addSell(Sell s){
idS++;
s.setId(idS);
sales.add(s);
}
public Sell findSell(int idS){
for(Sell sell : sales){
if(sell.getId()==idS){
return sell;
}
}
return null;
}
}
This is the error :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at controlLayer.SellCtr.addItemToSell(SellCtr.java:24)
at tuiLayer.SaleAddItemToSaleGUI$2.actionPerformed(SaleAddItemToSaleGUI.java:93)
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)
I have rebuild the project and the exceptions changed.
EDIT 3 : I have made idS static and now it works. Thanks a lot guys!
I suggest you
make sure you are compiling all your classes. A build tool like maven or gradle will help.
you use enum for singletons. These are thread safe and simpler.
disable the feature in eclipse which allows you to run code which doesn't compile. This only delays finding errors which makes them worse.
I would replace
public class SellContainer{
private ArrayList<Sell> sales;
private static int idS=0;
private static SellContainer instance=null;
public SellContainer(){
sales = new ArrayList<>();
}
public static SellContainer getInstance(){
if(instance == null){
instance = new SellContainer();
}
return instance;
}
with
public enum SellContainer {
INSTANCE;
private final List<Sell> sales = new ArrayList<>();
private int idS = 0;
Initiate the object before the return object is back to the called method.
In SellContainer, if condition failure leads to give back the Sell Object as NULL.
You need to modify this logic.
return null;
Say for example, if in a program you get a null-pointer error for adding a piece of code to your which program makes the program run fine but without that piece of code the program doesn't work as expected, would it be a good idea to allow the null-pointer error to happen, if so, is there any way of catching it before it displays onto the console. 1 way I am aware of is, using try and catch but in my past experience this hasn't worked, my attempt at using this might be wrong, but this is how I tried it.
try {
// line / s of code to catch the error from
} catch (java.lang.NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
edited: The list of error i am getting:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at playAGame.endGameResult(playAGame.java:204)
at playAGame.checkingWinner(playAGame.java:159)
at playAGame.callCheckWinner(playAGame.java:179)
at playAGame.moveSetup(playAGame.java:66)
at playAGame$1.actionPerformed(playAGame.java:52)
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.AWTEventMulticaster.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)
this is because of this line: button = new JButton[button.length][button.length];
I am creating a TicTacToe game and if I remove that line from my code, the game won't work properly.
edited: I believe this is one of the lines providing the null pointer, correct me if I am wrong. Basically, I have created a method checking if three given buttons have the value X, if it does then trigger the win variable to true. This is how I am checking if someone has won the TicTacToe game.
public void checkingWinner(JButton button1, JButton button2, JButton button3) {
if(buttonA.getText().equals(buttonB.getText()) && buttonB.getText().equals(buttonC.getText()) && buttonA.getText().equals("X"))
{
win = true;
System.out.pl("winner is X");
}
It's hard to tell without seeing the whole code, but it might be the case that the initialization you're doing of the array is throwing an exception since it's the first time it's being initialized, during which time it is being referenced.
If that's the case, you should solve this by using a constant for the width and height instead of self reference:
public static final int HEIGHT = ...;
public static final int WIDTH = ...;
...
button = new JButton[HEIGHT][WIDTH];
Are you sure that the line/s of code are throwing a NullPointerException? Because it works for me.
public class Main {
static String a;
public static void main(String args[]) {
try {
a.charAt(0);
} catch (java.lang.NullPointerException e) {
System.out.println("Thrown");
e.printStackTrace();
}
}
}