Getting NullPointerException in Java - java

I wrote a Minesweeper game that worked fine last week, but now when I try to run it, I get a NullPointerException, and I didn't change the code.
There is one thing that probably is the cause: I installed Ubuntu on my laptop 2 days ago and I tried to copy my user folder from Windows to my Ubuntu desktop. I stupidly used the "move here" option because I thought that would copy the folder (there wasn't any copy option). But when I logged back into Windows, it was as if I were a new user. So I copied that folder from my Ubuntu desktop back to Windows and fortunately all my files were back.
Here is my code. It does say MinesweeperBoard.show() is deprecated (that class extends JFrame), but the NullPointerException occurs at board = new MinesweeperBoard(9, 9, 10); even though I declared board before.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Do you want to play beginner (b), intermediate (i), or EXPERT (e)?");
String input = in.next();
MinesweeperBoard board;
if (input.equals("b"))
board = new MinesweeperBoard(9, 9, 10);
else if (input.equals("i"))
board = new MinesweeperBoard(16, 16, 40);
else if (input.equals("e"))
board = new MinesweeperBoard(30, 16, 99);
else
board = new MinesweeperBoard(30, 30, 100);
board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
board.show();
}
Further down in the stack trace, it points to this line of code in another class:
icons[0] = new ImageIcon(this.getClass().getClassLoader().getResource("0.gif"));
The stack trace line after that is at javax.swing.ImageIcon.<init>(Unknown Source)
I tried build all and clean, but doing those didn't fix anything.
Edited
Entire stack trace:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at MBox.<init>(MBox.java:25)
at MinesweeperBoard.<init>(MinesweeperBoard.java:50)
at MinesweeperGame.main(MinesweeperGame.java:16)
This is from MinesweeperBoard:
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
boxes[i][j] = new MBox(i, j); //Line 50
boxes[i][j].setBounds(i * SIZE + 5, j * SIZE + 65, SIZE, SIZE);
boxes[i][j].putSelfInBoard(this);
cont.add(boxes[i][j]);
}
}
This is from MBox:
icons = new ImageIcon[12];
icons[0] = new ImageIcon(this.getClass().getClassLoader().getResource("0.gif")); //Line 25
icons[1] = new ImageIcon(this.getClass().getClassLoader().getResource("1.gif"));
icons[2] = new ImageIcon(this.getClass().getClassLoader().getResource("2.gif"));
...

The NullPointerException is probably occurring because this.getClass().getClassLoader().getResource("0.gif") is returning null.

It sounds like the file "0.gif" isn't in your jar file (or wherever), so getClass().getClassLoader().getResource("0.gif") is returning null. That's then being passed to the ImageIcon constructor, which is throwing an exception.

its also possible the files have other rights after you have copied the files with ubuntu.
so you should check the rights of the files and wether they actually exits.

Related

Making an interactive GUI in Java for own program

To start with -- I'm not sure, that I have properly formulated the question (I'm new in Java and in making programs with GUI).
It is the following thing, I'm trying to do. I have a window with several similar parameters (numbers are just for distinction between lines and it ist just very simplified example, of what should my GUI be):
Initial Window
Then, by clicking on the "+"-button I would like to add an new line, like here:
Line 35 is added
It should be also possible to delete lines, like here: Line 30 was deleted, by pressing "-"-Button.
As I wrote at the beginning, it is possible, that there was such a question, but I couldn't find anything (probably, because I do not now the keywords or I was looking with a wrong ones).
How such window can be done? The only idea I have is to draw a new window after every +/-.
Addition: Code (not working in the part of changing the number of rows).
import javax.swing.*;
import java.awt.event.*;
public class Test extends JFrame {
public Test() {
setSize(200, 600);
JButton plusButton[] = new JButton[100];
JButton minusButton[] = new JButton[100];
JTextField fields[] = new JTextField[100];
JPanel panel1 = new JPanel();
for (int i=0; i<plusButton.length; i++) {
plusButton[i]=new JButton("+");
minusButton[i]=new JButton("-");
fields[i] = new JTextField("Text "+ i);
}
for (int i=1; i<4; i++) {
panel1.add(plusButton[i*10]);
plusButton[i*10].setActionCommand("add after " +String.valueOf(i));
panel1.add(minusButton[i*10]);
minusButton[i*10].setActionCommand("remove " +String.valueOf(i));
panel1.add(fields[i*10]);
}
panel1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
this.getContentPane().add(panel1);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
for (int i=0; i<100; i++) {
String stand1 = "add after "+String.valueOf(i);
String stand2 = "remove "+String.valueOf(i);
if (stand1.equals(e.getActionCommand())) {
//add "row" of elements
panel1.add(plusButton[i]);
plusButton[i+1].setActionCommand("add");
panel1.add(minusButton[i+1]);
minusButton[i+1].setActionCommand("remove");
panel1.add(fields[i+1]);
} else if (stand2.equals(e.getActionCommand())) {
//delete "row" of elements
}
}
}
public static void main(String[] args) {
Test a = new Test();
}
}
The Problem, that is obvious -- when I want to add 2 rows (i think it is proper definition) of buttons after button 20, there will be an doubling of numbers. As a solution I see here a creation of a new panel for each new row. But it is sounds wrong for me.
P.S. Unfortunately I do not have time to end this topic or to post a working example. I actually found some kind of solution, beginning from the Question here, on Stack Overflow:
Adding JButton to JTable as cell.
So, in case somebody will be looking for such topic, it should sounds like "jButton in jTable".
There are multiple GUI frameworks for Java. First decide which one you wanna use.
As for your particular query
Add functionality to the + and - such that it will create an instance of a field object (that line with parameters as you call them) or destroy that particular instance of the object.
+ is clicked -> Create new object on consecutive line and increase the pointer-count(?) of the following fields.
- is clicked -> Call destructor for the particular object and decrease the pointer-count of the following fields.

JAVACV videocapture read stops taking new pictures and just repeats the same one, why is it doing this?

I am currently using the Java Open Cv Library to take a series of consecutive images from a camera. The frame that is captured is then passed to another thread which saves the image.
But, for some reason after it takes a certain amount it stops taking new images and instead just repeats the previous one.
If i ask it to take 10 it stops at 5, and for 20 it stops at 11, so it isn't the same value each time.
The code is currently inside of a thread but i do not think that this is affecting it in any way.
Here is the current code.
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture camera = new VideoCapture(0);
camera.open(0);
Mat frame = new Mat();
for (int i = 0; i < 20; i++) {
camera.read(frame);
fileName = "Captures/" + timetoNano + ".png";
fileTime = timetoNano;
fileToSave = frame;
ImageProperties newProperties = new ImageProperties(fileName,
fileToSave, fileTime);
bufferImageProps.add(newProperties);
}
If i put camera.open(0) inside of the for loop, this does fix the issue, it does however decrease performance greatly and i don't think it has to be there as it works up until this "breaking point".
Any feedback would be greatly appreciated.
I think i have found the solution. I moved the line
Mat frame = new Mat();
Inside of the for loop.
Because of this it means that each time you capture a frame you are capturing it onto a null frame, this seems to fix the issue.

how do you add images to the project directory in eclipse?

I have a program that runs and doesnt throw a runtime error in eclipse which should set up an image to a JButton at the end of the program as the result but the image is never put on to the button. The program worked fine in DrJava but I transferred to eclipse in order to make a jar file.
I saw in another question posted that someone had a similar problem that said the images should be put into the project directory not the src directory but it didnt explain how to actually fix the problem... im new to eclipse so if someone could help me out id appreciate it thanks.
here is how the images are set up in my code:
public void tempSelection70 (int fRate, int wbTemp, int rcTons, int a, int r)
{
for (int model = 0; model < 7; model++)
{
MyArray y = new MyArray(tons70FCharts[model], "t");
int[][] x = y.getArray();
int t = x[a][r];
if (rcTons == t)
{
tableButton = new JButton(new ImageIcon(tablesFor70[model], tablesFor70[model]));
break;
}
else
{
tableButton = new JButton(new ImageIcon("CANNOT_FIND_MODEL.GIF", "SCROLL"));
}
}
for (int model = 0; model < 7; model++)
{
MyArray y = new MyArray(flow70FCharts[model], "f");
int[][] x = y.getArray();
int t = x[a][r];
if (fRate == t)
{
tableButton = new JButton(new ImageIcon(tablesFor70[model], tablesFor70[model]));
break;
}
else
{
tableButton = new JButton(new ImageIcon("CANNOT_FIND_MODEL.GIF", "SCROLL"));
}
}
}
You're passing a file name as argument. I guess this file name is a relative file name. So the file is relative to the directory from which your IDE launches the java command to execute your application: the working directory.
This directory can be changed from the run configuration in Eclipse, under the tab "Arguments". But this is probably not what you want. The icons should certainly be bundled with your application, and loaded with the class loader. Put them under a package in your source folder. Eclipse will copy them to the output directory, along with the compiled classes. And if you generate a jhar for your app, they will be bundled in the jar with your classes. Once this is done, you just have to use the constructor taking a URL as argument, and pass
SomeClassOfYourApp.getResource("/the/package/of/the/image.png")
as this URL argument.
This will allow you to bundle the icons with the app easily, and will load the icons whatever the working directory is.

Java is reading old input files, not new ones

I have some java code which reads text files, adds the contents to a vector and then prints these points to screen using a graph windower.
I have three pointdata.txt files, pointdata1.txt, pointdata2.txt and pointdata3.txt.
The problem i am having is that, even when i change the input file in my driver to pointdata1 or pointdata2, it still runs for pointdata3. I have ensured that there are no occurences of pointdata3 anywhere else in the code. It only appears twice, but i have made sure it is the same.
I have checked the files themselves, they are different. Checked and checked and checked the pathnames, they are different!
Even when i comment out every System.out.println() in the entire code, it still prints everything!
It is asif the code is no longer refereing the the text files, or even running, eclipse just keeps printing what was previously added to the viewport?
Here is the code from my driver:
import java.util.*;
public class PointDriver {
private PointField pointfield;
// testing
public void doAllTests() throws Exception{
this.test1();
this.test2();
}
// Display all points in the file
public void test1() throws Exception{
SimpleIO sIO = new SimpleIO();
System.out.println("Contents of Point File: ");
sIO.displayFile("pointdata1.txt");
//sIO.displayFile("pointdata2.txt");
//sIO.displayFile("pointdata3.txt");
System.out.println();
}
// Load points from a file into a vector and echo them back to the screen
// This uses the StringTokenizer to split the lines into two Strings, then
// uses the Point class to assign the two Strings to x,y double variables
// which form Points. Within the same loop, the points are also displayed
// in a window using the Graph Window class. Maximum x and y values are used
// to determine the dimensions of the GraphWindow, adding 10 units to each
// value to provide a border.
public void test2() throws Exception{
System.out.println("Contents of Point File: ");
System.out.println();
System.out.println("Points are Displayed in a Graph Window");
System.out.println();
Vector lines;
lines = pointfield.getlines("pointdata1.txt");
//lines = pointfield.getlines("pointdata2.txt");
//lines = pointfield.getlines("pointdata3.txt");
Iterator IT;
IT = lines.iterator();
Vector v;
v = new Vector();
double maxX, maxY;
PointField pointfield;
pointfield = new PointField();
GraphWindow gw;
gw = new GraphWindow();
while (IT.hasNext()) {
StringTokenizer st;
String ID = (String)IT.next();
st = new StringTokenizer(ID);
double x = Double.parseDouble(st.nextToken());
double y = Double.parseDouble(st.nextToken());
Point p;
p = new Point(x,y);
v.addElement(p);
int i = v.size();
System.out.println("Point ID: " +i+ " X: "+x+", Y: "+y);
gw.plotPoint(x, y);
}
this.pointfield = new PointField(v);
maxX = this.pointfield.findMaxXPoint();
maxY = this.pointfield.findMaxYPoint();
int width = (int)maxX + 10;
int height = (int)maxY + 10;
gw.setMap(width, height);
}
// Short main method to kick of all tests sequence in doAllTests method
public static void main(String[] args) throws Exception {
PointFieldDriver pfd;
pfd = new PointFieldDriver();
pfd.doAllTests();
}
}
It looks like Eclipse is running an old version of your class file. I'm gathering this as you said that you commented out the printlns, but the output is still displaying.
A few things to check:
In the menu, make sure that Project > Build Automatically is set. If that isn't set, set it, and your problem should be solved.
See whether the timestamp on your class file is changing when you change the source. If it isn't, then Eclipse isn't recompiling it for some reason. You can find the class file probably under the bin folder (if you are using the Eclipse project defaults).
If you find the timestamp is old, try removing the bin folder from outside of Eclipse. Next, right-click on the project and select refresh. Finally, select Project > Clean. This should cause the code to be recompiled into a new class file.

JavaPlot and gnuplot

I'm desperately trying to get Java and gnuplot to play nice. I've started using JavaPlot and have added the jar to the classpath (using Eclipse).
I've also downloaded gnuplot and have placed it in a safe place.
First question, all examples given by JavaPlot are assuming you have put gnuplot in the right place, where this is I have no idea. Therefore their example of:
import com.panayotis.gnuplot.JavaPlot;
public class test {
public static void main(String[] args) {
JavaPlot p = new JavaPlot();
p.addPlot("sin(x)");
p.plot();
}
}
Will only work if gnuplot is added to the classpath, any ideas on where that might be and how?
Not to worry though, as you can define the location of gnuplot in the constructor of JavaPlot, like so:
import com.panayotis.gnuplot.JavaPlot;
public class test {
public static void main(String[] args) {
JavaPlot p = new JavaPlot("D:/Eclipse/gnuplot/binary/pgnuplot.exe");
p.addPlot("sin(x)");
p.plot();
}
}
This does something, if you're quick you can see a graph appear (correctly, can see the sine wave) and then immediately disappear. I've read online that in the actual gnuplot application this is common when using Windows and that a '-persist' must be added after the plot. Fortunately JavaPlot also has a function that does that:
p.setPersist(true);
But in my case it does nothing. So second question, anyone used gnuplot, JavaPlot, and Windows 7 64bit before and know how to do this? From my Googling I understand pgnuplot is the correct .exe to run?
What am I missing? What am I doing wrong?
I think I may have a workaround for you, as I ran into the same sort of thing today when accessing JavaPlot on Windows 7 (32 bit here though). Yes, pgnuplot.exe is the one you want, however you do not need to explicitly setPersist if you do not want to because JavaPlot does that for you. What I had to do was go through the source code and comment out a line.
In GnuPlotParameters, I see the code
/* Finish! */
bf.append("quit").append(NL);
This is lines 198-199. Then the plot windows stays open. Now, what this also does is leave open gnuplot. If you do not mind, you can see your graphs this way. Have not figured out yet how to close gnuplot while leaving the plot window open.
EDIT:
Maybe a more appropriate way is not to comment out line 199 and go with this:
bf.append("pause -1").append(NL);
/* Finish! */
bf.append("quit").append(NL);
In this manner, the pause dialog comes up. This allows you to see the plot. When you dismiss the dialog, everything goes bye-bye.
Try JavaGnuplotHybrid: https://github.com/mleoking/JavaGnuplotHybrid
It solves the problem of immediately disappear.
Here is the example for a 2D plot:
public void plot2d() {
JGnuplot jg = new JGnuplot();
Plot plot = new Plot("") {
{
xlabel = "x";
ylabel = "y";
}
};
double[] x = { 1, 2, 3, 4, 5 }, y1 = { 2, 4, 6, 8, 10 }, y2 = { 3, 6, 9, 12, 15 };
DataTableSet dts = plot.addNewDataTableSet("2D Plot");
dts.addNewDataTable("y=2x", x, y1);
dts.addNewDataTable("y=3x", x, y2);
jg.execute(plot, jg.plot2d);
}
I use eclipse for debugging and happen to be using this package. I figured out how to fix this. Add the following to your code. The setPersist(true) doesn't seem to work for some reason.
p.set("term", "x11 persist");
try this
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("D:/Projet/X-Gnuplot_4.6.0_rev6/Bin/gnuplot/bin/gnuplot.exe");
java.io.OutputStream opStream = proc.getOutputStream();
PrintWriter gp = new PrintWriter(new BufferedWriter(new OutputStreamWriter(opStream)));
gp.println("plot sin(x); pause mouse close;\n");
gp.close();
int exitVal = proc.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
it works for me
replace your
p.addPlot("sin(x)");
by
p.addPlot("sin(x); pause 100;");
it only appears for 100 seconds
fsd

Categories

Resources