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.
Related
I am running into issues with LibGDX on Desktop. I keep getting the following error when trying to launch the application:
Exception in thread "main" java.lang.UnsatisfiedLinkError: com.badlogic.gdx.utils.BufferUtils.newDisposableByteBuffer(I)Ljava/nio/ByteBuffer;
at com.badlogic.gdx.utils.BufferUtils.newDisposableByteBuffer(Native Method)
at com.badlogic.gdx.utils.BufferUtils.newUnsafeByteBuffer(BufferUtils.java:288)
at com.badlogic.gdx.graphics.glutils.VertexArray.<init>(VertexArray.java:62)
at com.badlogic.gdx.graphics.glutils.VertexArray.<init>(VertexArray.java:53)
at com.badlogic.gdx.graphics.Mesh.<init>(Mesh.java:148)
at com.badlogic.gdx.graphics.g2d.SpriteBatch.<init>(SpriteBatch.java:173)
at com.badlogic.gdx.graphics.g2d.SpriteBatch.<init>(SpriteBatch.java:142)
at com.badlogic.gdx.graphics.g2d.SpriteBatch.<init>(SpriteBatch.java:121)
at com.badlogic.gdx.graphics.g2d.SpriteBatch.<init>(SpriteBatch.java:115)
I have the following libraries added to my project:
gdx.jar
gdx-sources.jar
gdx-natives.jar
gdx-backend-lwjgl.jar
gdx-backend-lwjgl-natives.jar
Am I missing something?
I have searched high and low, but everything I find is for Android and tells me to add the .so libs from the arm folders to my project, but that doesn't make sense to me for a desktop project on wintel platform.
I'd advise you to setup your projects with this GUI. It should provide you with a valid setup for all platforms. You may also use the latest nightly builds and check if the problem still occurs. The problem might be that the native libraries do not match the other jars.
Another problem might be that you instantiate a SpriteBatch (or something else which internally uses a SpriteBatch) too early (looked a bit like this in the stacktrace). For example statically like this:
private static SpriteBatch batch = new SpriteBatch();
This won't work, since libgdx wasn't setup correctly at this point in time. Instead, create such things in the create/show methods of your game.
Use the following main method body to launch the object:
static public void main(String[] args) throws Exception {
// SkeletonViewer.args = args;
String os = System.getProperty("os.name");
float dpiScale = 1;
if (os.contains("Windows")) {
dpiScale = Toolkit.getDefaultToolkit().
getScreenResolution() / 96f;
}
if (os.contains("OS X")) {
Object object = Toolkit.getDefaultToolkit().getDesktopProperty(
"apple.awt.contentScaleFactor");
if (object instanceof Float && ((Float) object).intValue() >= 2) {
dpiScale = 2;
}
}
if (dpiScale >= 2.0f) {
uiScale = 2;
}
LwjglApplicationConfiguration.disableAudio = true;
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.width = (int) (800 * uiScale);
config.height = (int) (600 * uiScale);
config.title = "Skeleton Viewer";
config.allowSoftwareMode = true;
config.samples = 2;
new LwjglApplication(new SampleApplication(), config);
}
I stumpled upon a Problem with Java wich seems very strange so I didn't found anything in the internet.
I want to make a little program wich just searchs for specific files to delete them. (Not at this point yet) Right now, the Program just searchs for all files in the dir and in the subdirectories. It works but sometimes (about 50/50) the JList, I use to show the files, does not show anything. (This is the problem I have) I dont change any Files, nothing changes to the .jar, it just does not show the elements sometimes.
I also checked if the array is maybe empty, there are elements in it, even when the List does not show them. It would be greate if you know a solution to this. Thank you.
Here is the Code: (Just so you know, I did not wrote the function GetAllFiles by my own)
Variables:
JList output;
JScrollPane outputScrollPanel;
DefaultListModel outputContent;
String[] files;
int fileIndex;
File source;
Constructor:
add(output = new JList());
outputContent = new DefaultListModel();
output.setModel(outputContent);
add(outputScrollPanel = new JScrollPane(output));
outputScrollPanel.setBounds(20, 20, getWidth() - 50, getHeight() - 40);
files = new String[0];
fileIndex = 0;
SearchFiles();
The SearchFiles-function together with the GetAllFiles (I did my best, not taking redundant Names ;) )
private void SearchFiles() {
source = new File("");
GetAllFiles(source);
for(int i = 0; i < fileIndex; i++) {
outputContent.addElement(files[i]);
}
}
private void GetAllFiles(File dir) {
File[] fileList = dir.getAbsoluteFile().listFiles();
if (fileList != null) {
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].isDirectory()) {
GetAllFiles(fileList[i]);
} else {
if(fileIndex%100 == 0) {
IncreaseFileListSize();
}
// i am so proud of this one: (it just adds the relative path + file name to the files-array
files[fileIndex] = fileList[i].toString().substring(source.getAbsolutePath().toString().length()+1);
fileIndex++;
}
}
}
}
I've managed to add an image into a JPanel in netbeans and display it.I wonder how to get to the next one,by pressing a button.
I've added the image using this code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
// TODO add your handling code here:
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(null);
if ( result == JFileChooser.APPROVE_OPTION ){
String Ruta = fileChooser.getSelectedFile().getAbsolutePath();
jTextField1.setText(Ruta);
Icon icon = new ImageIcon(Ruta);
jLabel2.setIcon(icon);
JOptionPane.showMessageDialog(this,"You chose to open this file: " +
fileChooser.getSelectedFile().getName());
}
}
And when i press a button called "jButton2" to get the next image,without manually selecting it again from folder.
For example:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){
// TODO add your handling code here:
}
Thank You very much.
You have to enumerate images in the directory you are browsing in. When the user selects the file, you should keep a list of all images from that directory in order to retrieve them when user click the next button. As well you can get the file list whenever the user clicks the next button.
maybe something like this:
private File allFiles;
private int currentIndex;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(null);
if ( result == JFileChooser.APPROVE_OPTION ){
currentFile = fileChooser.getSelectedFile();
String Ruta = currentFile.getAbsolutePath();
jTextField1.setText(Ruta);
allFiles = currentFile.getParent().listFiles(); // maybe you need a filter to include image files only....
currentIndex = indexOf(allFiles, currentFile);
Icon icon = new ImageIcon(Ruta);
jLabel2.setIcon(icon);
JOptionPane.showMessageDialog(this,"You chose to open this file: " + fileChooser.getSelectedFile().getName());
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
if (currentIndex+1 < allFiles.length) {
jtextField1.setText(allFiles[++currentIndex]);
}
}
private int indexOf(File[] files, File f) {
for (int i=0; i+1 < files.length; i++) {
if (files[i].equals(f)) {
return i;
}
}
return -1;
}
Get the parent file if the current image (File.getParent()).
Use one of the File.list..() methods to get the image files.
Sort them into some order that means 'next' to the user.
Iterate that connection until you find the current File then display the next one after that.
I am assuming that you want the next image, if possible in the same directory you chose in your first code excerpt. What you could do is that once the user has chosen the image, you could use Apache's FileUtils to get the extension of files. If the file is a JPG, JPEG, PNG, etc you could load it's location in a List of strings.
This will give you a list of picture paths. You could then use the buttons to traverse the list. Once the button is pressed, you move to the next item, load the image and render it.
EDIT: This is how I would go about it step by step:
Create a global variable of type List.
Create a global variable which will act as a counter;
In your jButton1ActionPerformed method:
Get the parent directory of the file that the user has chosen;
Use Apache's FileUtil class to get the extension of the file names. If the file name is an image, such as PNG, JPG, etc, add it (the path of that file) to your list.
In you jButton2ActionPerformed, increment the counter (if the counter is not smaller than the size of your list, re-initialize it to 0, so as to avoid OutOfBoundsExceptions) and load the the file denoted by the counter using similar logic to your jButton1ActionPerformed method.
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.
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.