Null pointer exception when access index of a DefaultListModel - java

I have a list:
JList characterList = new JList(characterListModel);
characterListModel = new DefaultListModel();
String myCharacters[]={"Dean Winchester","Sam Winchester",
"Bobby Singer","Castiel"};
for (String myCharacter : myCharacters) {
((DefaultListModel) characterList.getModel()).addElement(myCharacter);
}
And I've written a method, in a seperate class, to remove a character at a selected index:
public void removeCharacter() {
DefaultListModel characterListModel = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterListModel();
JList characterList = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterList();
int idx = characterList.getSelectedIndex(); //<---line 62
int size = characterListModel.getSize();
characterListModel.remove(idx);
if (size == 0) {
//do nothing
} else {
if (idx == characterListModel.getSize()) {
idx--;
}
characterList.setSelectedIndex(idx);
characterList.ensureIndexIsVisible(idx);
}
}
However when I run it with my button, I get this stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.detica.LarpDB.Controller.Controller.removeCharacter(Controller.java:62)
at com.detica.LarpDB.view.PlayerContentPane$3.actionPerformed(PlayerContentPane.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$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$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)
A lot of the issues I've seen googling this, stem from the line: DefaultListModel characterListModel = ....
And the issue they have is that their creating a new instance of the object, now I''m only new to this whole Java thing, but this shouldn't be an issue with me, as I've not made anythign new, I've just been specific about which object this is.
Please could someone help me untangle myself?

Those 2 lines can create a lot of problems:
DefaultListModel characterListModel = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterListModel();
JList characterList = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterList();
If any of the chained methods return null (for whatever reason) the line will throw a NullPointerException.
I suggest you break them down in several lines and check the value of each call to see where you get the null from.
EDIT
Just realised that line 62 is int idx = characterList.getSelectedIndex();. It means that characterList is null.

If it's failing on the line that you indicated is line 62, then the only object referenced on that line, and therefore the only thing that could be null, is characterList. This implies that your getCharacterList function is returning null. (If the error was inside the getSelectedIndex function, then you would have another line in your stack trace.)
As you didn't post the getCharacterList function, I can't say much more. But you should take a look at that function and see under what circumstances it could return null.

Related

OptaPlanner Nurse Rostering accumulate sum Null Pointer Exception

I try to modify the OptaPlanner nurse Roster example.
So far, I want to write a rule in the drl file which reacts when an employee works more than 13 hours per day.
I expanded the class shiftType to get hours per Shift.
At first look, the rule seems to work but when there is no feasible solution after a while I get a NullPointerException.
Here is some relevant code:
rule "dailyRestPeriod"
when
ShiftAssignment($employee : employee, $shiftType : shiftType, $shiftDate : shiftDate, $employee!=null)
$dailyTotalHours : Number( intValue > 13) from accumulate(
$assignmentEmployee: ShiftAssignment(employee == $employee, shiftDate == $shiftDate),
sum($assignmentEmployee.getShiftType().getShiftDurationHours())
)
then
System.out.println("Employee " +$employee +" dailyTotal " +$dailyTotalHours);
scoreHolder.addHardConstraintMatch(kcontext, - 1);
end
And part of the Exception
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Solving failed.
at org.optaplanner.examples.common.swingui.SolverAndPersistenceFrame$SolveWorker.done(SolverAndPersistenceFrame.java:319)
at javax.swing.SwingWorker$5.run(Unknown Source)
at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.run(Unknown Source)
at sun.swing.AccumulativeRunnable.run(Unknown Source)
at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.actionPerformed(Unknown Source)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.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)
Caused by: java.lang.RuntimeException: java.lang.NullPointerException
at org.drools.core.rule.SingleAccumulate.reverse(SingleAccumulate.java:124)
at org.drools.core.phreak.PhreakAccumulateNode.removeMatch(PhreakAccumulateNode.java:806)
at org.drools.core.phreak.PhreakAccumulateNode.removePreviousMatchesForRightTuple(PhreakAccumulateNode.java:865)
at org.drools.core.phreak.PhreakAccumulateNode.doRightUpdates(PhreakAccumulateNode.java:444)
at org.drools.core.phreak.PhreakAccumulateNode.doNode(PhreakAccumulateNode.java:87)
at org.drools.core.phreak.RuleNetworkEvaluator.switchOnDoBetaNode(RuleNetworkEvaluator.java:534)
at org.drools.core.phreak.RuleNetworkEvaluator.evalBetaNode(RuleNetworkEvaluator.java:505)
at org.drools.core.phreak.RuleNetworkEvaluator.evalNode(RuleNetworkEvaluator.java:341)
at org.drools.core.phreak.RuleNetworkEvaluator.innerEval(RuleNetworkEvaluator.java:301)
at org.drools.core.phreak.RuleNetworkEvaluator.outerEval(RuleNetworkEvaluator.java:136)
at org.drools.core.phreak.RuleNetworkEvaluator.evaluateNetwork(RuleNetworkEvaluator.java:94)
at org.drools.core.phreak.RuleExecutor.reEvaluateNetwork(RuleExecutor.java:194)
at org.drools.core.phreak.RuleExecutor.evaluateNetworkAndFire(RuleExecutor.java:73)
at org.drools.core.common.DefaultAgenda.fireNextItem(DefaultAgenda.java:970)
at org.drools.core.common.DefaultAgenda.fireLoop(DefaultAgenda.java:1312)
at org.drools.core.common.DefaultAgenda.fireAllRules(DefaultAgenda.java:1251)
I don't understand why but when i change the rule a little bit it works fine when i broke down the rule.
Perhaps it has something to do with planning variables and planning entity,.. but I'm not sure.
Here is the code how it looks like now:
rule "dailyRestPeriod"
when
$employee : Employee()
$shift : Shift( $shiftType : shiftType , $shiftDate :shiftDate )
$dailyTotalHours : Number( intValue >= 13) from accumulate(
$assignmentEmployee: ShiftAssignment(employee == $employee, shiftDate == $shiftDate),
sum($assignmentEmployee.getShiftType().getShiftDurationHours())
)
then
scoreHolder.addHardConstraintMatch(kcontext, - 1);
end

Java JComboBox ActionListener crash

I'm getting
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: -1
when I'm deleting last Item in JComboBox. Anyone knows why?
cb = new JComboBox<String>();
bComboDelete.addActionListener(this);
bComboDelete = new JButton("X"); //deletes item from CB
bComboAccept = new JButton("#");// add an item
ArrayList<String> names = new ArrayList<String>(); //get name, runs with sNumbers
ArrayList<String> sNumbers = new ArrayList<String>();//some String numbers ----> e.g. [[1, 2, 3],[4, 5, 6]]
ArrayList<Integer> numbers = new ArrayList<Integer>(); //array to temp hold numbers
//***ending code from ActionListener
else if(s == bComboAccept)
{
sNumbers.add(numbers.toString());
//System.out.println(sNumbers);
names.add(tName.getText());//tName is JTextField
//cb.addItem(tName.getText());
cb.addItem(new String(tName.getText()));
cb.setSelectedItem(new String(tName.getText()));
}
else if(s == bComboDelete)
{
int z = cb.getSelectedIndex();
//System.out.println(z);
names.remove(z);
//System.out.println("Names: "+names);
sNumbers.remove(z);
//System.out.println("sNumbers: "+sNumbers);
cb.removeItem(cb.getSelectedItem());
}
else if(s == cbLista)
{
System.out.println("cb Action listener!\n--------------");
Integer i = cb.getSelectedIndex();
tNames.setText(nazwy.get(i));
tNumbers.setText("");//also TextField
numbers.clear();
numbers=arrayStringToIntegerArrayList(sNumbers.get(i));
tNumbers.setText(numbers.toString().substring(1, numbers.toString().length()-1));
}
Rest of crash code:
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: -1 at
java.util.ArrayList.elementData(Unknown Source) at
java.util.ArrayList.get(Unknown Source) at
Okno.actionPerformed(Okno.java:339) at
javax.swing.JComboBox.fireActionEvent(Unknown Source) at
javax.swing.JComboBox.contentsChanged(Unknown Source) at
javax.swing.AbstractListModel.fireContentsChanged(Unknown Source) at
javax.swing.DefaultComboBoxModel.setSelectedItem(Unknown Source) at
javax.swing.DefaultComboBoxModel.removeElementAt(Unknown Source) at
javax.swing.DefaultComboBoxModel.removeElement(Unknown Source) at
javax.swing.JComboBox.removeItem(Unknown Source) at
Okno.actionPerformed(Okno.java:328) 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$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)
Try adding the following modifications...
else if(s == bComboDelete)
{
int z = cb.getSelectedIndex();
// -1 means that no item is selected
if (z > -1) {
//System.out.println(z);
names.remove(z);
//System.out.println("Names: "+names);
sNumbers.remove(z);
//System.out.println("sNumbers: "+sNumbers);
cb.removeItem(cb.getSelectedItem());
}
}
else if(s == cbLista)
{
System.out.println("cb Action listener!\n--------------");
Integer i = cb.getSelectedIndex();
// -1 means that no item is selected
if (i > -1) {
tNames.setText(nazwy.get(i));
tNumbers.setText("");//also TextField
numbers.clear();
numbers=arrayStringToIntegerArrayList(sNumbers.get(i));
tNumbers.setText(numbers.toString().substring(1, numbers.toString().length()-1));
}
}
It seems I fixed this.
Now code is like this:
I'm too lazy to rename the var to eng. Please ignore System out.
so:
nazwy = names
oceny = numbers
sOceny = sNumbers
cbLista = cb
tNazwa = tNames
tOceny = tNumbers
//----
else if(s == bComboDelete)
{
Object o = cbLista.getSelectedItem();
int z = nazwy.indexOf(o);
if(z>-1)
{
sOceny.remove(z);
nazwy.remove(z);
cbLista.removeItemAt(z);
System.out.println("Oceny w bloku delete(if)"+oceny.toString());
}
System.out.println("Oceny w bloku delete(poza if)"+oceny.toString());
}
else if(s == cbLista)
{
Object o = cbLista.getSelectedItem();
int z = nazwy.indexOf(o);
if(z>-1)
{
tNazwa.setText(nazwy.get(z));
oceny.clear();
oceny=arrayStringToIntegerArrayList(sOceny.get(z));
tOceny.setText(oceny.toString().substring(1, oceny.toString().length()-1));
System.out.println("Oceny w bloku CB"+oceny.toString());
}
else
{
tNazwa.setText("");
tOceny.setText("");
oceny.clear();
}
}

java Null Pointer exception in Noughts and Crosses project

I have been working on a project and the project is to create a game of Noughts and Crosses. I have already established the groundwork for the game and I'm currently developing it further. However , when I run the program and the AI is chosen to make the first move , I was returned a Java Null pointer exception in this line :
if(Game.Board[0][0].getText().equals(Game.Board[1][1].getText()) && Game.Board[0][0].getText().equals(Game.PlayerMark))
Game.Board[a][b] consists of 3x3 Jbuttons. PlayerMark is a string that either can contain "X" or "O".
How to solve this problem?
Where AI method is being called:
public void StartGame()
{
SideAssigner();
State = true;
if ( AIGame == true && FirstTurn ==true)
{
Computer.AI();
}
while ( State = true )
{
WinValidator();
}
}
Message in console box :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Computer.AI(Computer.java:19)
at Game.StartGame(Game.java:179)
at Game$10.actionPerformed(Game.java:739)
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$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.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 Sour
Update :
Here is an example of how each JBUtton's properties are determined:
Button1.setText("");
Button1.setEnabled(false);
Button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if ( State == true && playerO == true && PlayerGame == true )
{
isEmpty = false;
Button1.setText("O");
// WinValidator
// TurnChecker ??
}
else if ( State == true && playerX == true && PlayerGame == true )
{
isEmpty = false;
Button1.setText("X");
// WinValidator
// TurnChecker
}
else if ( State == true && computerO == true && AIGame == true)
{
isEmpty = false;
// Call Computer Class
// WinValidator
// TurnChecker
}
else if ( State == true && computerX == true && AIGame == true)
{
isEmpty = false;
// Call Computer Class
// WinValidator
// TurnChecker
}
}
});
AI Method ( snippet of it otherwise it would be too much to display) :
public static void AI()
{
for(int i=0; i<3; i++ )
{
for (int j=0; j<3; j++)
{
// Diagonal Defensive Strategy
if(Game.Board[0][0].getText().equals(Game.Board[1][1].getText()) && Game.Board[0][0].getText().equals(Game.PlayerMark))
{
if( !Game.Board[2][2].getText().equals(Game.ComputerMark) && !Game.Board[2][2].getText().equals(Game.PlayerMark))
{
Game.Board[2][2].setText(Game.ComputerMark);
MadeMove = true;
return;
}
}
if(Game.Board[2][2].getText().equals(Game.Board[1][1].getText()) && Game.Board[2][2].equals(Game.PlayerMark))
{
if( Game.Board[0][0].getText().equals(Game.ComputerMark) && !Game.Board[0][0].getText().equals(Game.PlayerMark))
{
Game.Board[0][0].setText(Game.ComputerMark);
MadeMove = true;
return;
}
}
if(Game.Board[0][0].getText().equals(Game.Board[1][1].getText()) && Game.Board[0][0].getText().equals(Game.PlayerMark))
{
if( !Game.Board[2][2].getText().equals(Game.ComputerMark) && !Game.Board[2][2].getText().equals(Game.PlayerMark))
{
Game.Board[2][2].setText(Game.ComputerMark);
MadeMove = true;
return;
}
}
Here is how to solve a NullPointerException. You should learn how to solve these problems yourself as you will get a lot of them:
Look at your stack trace:
at Computer.AI(Computer.java:19)
at Game.StartGame(Game.java:179)
Find the line at the top of the trace:
if(Game.Board[0][0].getText().equals(Game.Board[1][1].getText()) && Game.Board[0][0].getText().equals(Game.PlayerMark))
If you can't see the error, split the line up into smaller statements:
tmp = Game.Board[0];
tmp2 = tmp1[0];
tmp3 = Game.Board[1];
tmp4 = tmp3[1];
etc, etc - I am not sure what the types are, but you will know that.
Run it again and see where it falls over. The line number will now tell you exactly which statement has failed. The reference in that statement must be null.
If you don't know why the reference is null, follow the logic back and repeat the changes above.
You could also learn to use the debugger in an IDE such as Eclipse.

Combobox Selected Item

Here is my array of Strings :
String[] selection = { "0 + 0", "0.88 + 0.21", "-0.21 + 0.77", "-1.23 + 0.03" };
I then create a JComboBox:
JComboBox<String> jcb = new JComboBox<String>(selection);
jcb.addActionListener(new ComboListener());
Here is the ActionListener :
public class ComboListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComboBox<String> cb = (JComboBox<String>) e.getSource();
String selection = (String) cb.getSelectedItem();
String[] parts = selection.split(" + ");
System.out.println(parts[0]);
System.out.println(parts[1]);
}
}
Here's what is printed out when I select an option, say 0.88 + 0.21:
0.88 + 0.21
With the error:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
at GUI$ComboListener.actionPerformed(GUI.java:140)
at javax.swing.JComboBox.fireActionEvent(Unknown Source)
at javax.swing.JComboBox.setSelectedItem(Unknown Source)
at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup$Handler.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 javax.swing.plaf.basic.BasicComboPopup$1.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)
Anyone got any idea where I'm going wrong? My logic of splitting up the string seems to be fine. Many thanks;
split takes a regular expression as parameter. But + is a special regexp character. So you need to escape it:
String[] parts = selection.split(" \\+ ");
Another solution would be to use Pattern.quote:
String[] parts = selection.split(Pattern.quote(" + "));
String[] selection = {"0 + 0", "0.88 + 0.21", "-0.21 + 0.77", "-1.23 + 0.03"};
for(String s : selection){
System.out.println(Arrays.toString(s.split(" \\+ ")));
}
Successfully prints:
[0, 0]
[0.88, 0.21]
[-0.21, 0.77]
[-1.23, 0.03]
As the exception points out, the split doesn't work the way you intended (thought it would):
selection.split(" + ");
The problem is that split takes a regular expression so you need to escape the +
selection.split(" \\+ ");

NullPointerException that should not occur

I am sorry to post that in case it is just something stupid I am doing, but I hope there is some weird Java thing causing this that I am unaware of and can that will help others. Am I overlooking something here? Why the NPE?
Here is my code:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
int itemSoldCount = Integer.parseInt(afterAt[1]);
System.out.println("itemSoldCount: " + itemSoldCount);
ShopJInternalFrame.shopHolderWAIType = new JLabel[itemSoldCount];
int i = 2;
for (int k = 0; k < itemSoldCount; k++){
String waiType = afterAt[i];
System.out.println("ShopJInternalFrame.shopHolderWAIType.length: " + ShopJInternalFrame.shopHolderWAIType.length);
System.out.println("waiType: " + waiType);
System.out.println("k: " + k);
ShopJInternalFrame.shopHolderWAIType[k].setText(waiType); //line 530
Here is my output:
itemSoldCount: 2
ShopJInternalFrame.shopHolderWAIType.length: 2
waiType: A
k: 0
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.jayavon.game.client.MyCommandReceiver$8.run(MyCommandReceiver.java:530)
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)
ShopJInternalFrame.shopHolderWAIType = new JLabel[itemSoldCount];
This allocates storage for the array, but not for any JLabel objects. The array contains all nulls at this point. When you reach
ShopJInternalFrame.shopHolderWAIType[k].setText(waiType);
shopHolderWAIType[k] is null.
ShopJInternalFrame.shopHolderWAIType[k] will be null because you have not allocated any memory for individual array member. So you need to do this before you use the array member.
ShopJInternalFrame.shopHolderWAIType[k] = new new JLabel();

Categories