JList doesn't show Content 50% of the Time - java

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++;
}
}
}
}

Related

How can I write the name of an image and its coordinates into a save.txt file?

How would I write "if sticker1 is placed and in the array" then... My goal is for the sticker to be placed and entered into the array as a name with coordinates then saved to a save.txt file. From there, I can click a load button and it will load the sticker and place it at the exact coordinates.
if (hatSoundPlay){ //if hatSoundPlay is true
hatsound.play(); //and a hatsound will play
sticker sticker1 = new sticker();//creates a new sticker1
sticker1.arraysticker(hatPicture, "hat.png", clickX, clickY);//places sticker
image ++;//increments image by 1
arraysticker[image] = sticker1;//puts sticker 1 into the array
Then for the save code.
else if (savePicture.isPointInElement(clickX, clickY)){
FileWriter fw = new FileWriter("save.txt");
for (int i = 0; i < arraysticker.length; i++);
if (sticker1.images[images].isShowing){
//I want the iff statement ^^ to say if sticker if placed in the array
//fw.write name and coords into save.txt
}
}
You should have class Stricker, which should looks like this :
public class Sticker(){
private String name;
private int X;
private int Y;
//There You should place Getters and Setters to variables name,X and Y
//... and your method named 'arraysticker(Object, Image, Integer, Integer)'
}
... next step is to create the correct type of list ArrayList<Sticker> list = new ArrayList<>();
I'll do this like that:
if(hatSoundPlay){
hatsound.play();
Sticker sticker1 = new Sticker();
sticker1.arraysticker(hatPicture, "hat.png", clickX, clickY);
image ++;
list[image] = sticker1;
}
and finally at your save code should looks like:
else if (savePicture.isPointInElement(clickX, clickY)){
FileWriter fw = new FileWriter("save.txt");
for(int i = 0; i < list.length; i++){
if(list[i]!=null){ //if object exist, do...
String name;
int x,y;
name = list.getName();
x = list.getX();
y = list.getY();
fw.write(name + " " + x + " " + y + "\n"); //write all elements to file separated with space and symbol of new line
}
}
fw.close(); //necessary to close connection with file
}
To solve this problem I need rest of code, because I don't have information about Yours methods and otherr arrays like images
As far as you need save and restore objects, I suggest you to use some ready solutions like Jackson library. This simplifies the logic and you can control what to save and restore just by using annotations.
There are a lot of examples. So you get your class, mark properties with annotations and that is. Jackson lib will do everything for you. Take a look this tutorial: http://www.journaldev.com/2324/jackson-json-processing-api-in-java-example-tutorial

Libgdx : .Flip() inside a for loop

Am i implementing this correctly? I'm having issues with the direction my character is in, yet the state manager is working correctly. I'm unsure whether this is the problem. I have my player facing right automatically when constructed yet he faces left.
I have two arrays for both right and left animation inside my assets manager, The original images are facing right, i declare that array and then flip the same image on the left array. Does the left array override the right?
int idleRIndex = 1;
TextureRegion[] idleRight = new TextureRegion[3];
for (int i = 0; i < idleRight.length; i++)
{
idleRight[i] = rubenSprite.findRegion("iframe" + idleRIndex);
idleRIndex++;
}
rubenIdleRight = new Animation(0.2f, idleRight);
int idleLIndex = 1;
TextureRegion[] idleLeft = new TextureRegion[3];
for (int i = 0; i < idleLeft.length; i++)
{
idleLeft[i] = rubenSprite.findRegion("iframe" + idleLIndex);
idleLeft[i].flip(true, false);
idleLIndex++;
}
rubenIdleLeft = new Animation(0.2f, idleLeft);
It seems so after a test. The findRegion("iframe" + idleLIndex) and for the right are returning the same object reference. So I think the flip for the left will also affect the right. Maybe you can create a new TextureRegion object from the atlas. It shouldn't be much overhead. Try:
idleLeft[i] = new TextureRegion(rubenSprite.findRegion("iframe" + idleLIndex));
Then the flip shouldn't affect the right anymore.

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.

Deleting node childs of a Java JTree structure

I have a ftp program that retrieve folder data each time expanded. It does this by using a model like this:
private void FilesTreeTreeExpanded(javax.swing.event.TreeExpansionEvent evt) {
String path = new String("");
DefaultMutableTreeNode chosen = (DefaultMutableTreeNode) evt.getPath().getLastPathComponent();
String[] pathArray = evt.getPath().toString().replaceAll("]", "").split(",");
for (int i = 1 ; i < pathArray.length ; i++) path += "/"+ pathArray[i].trim();
// i were aded chosen.removeAllChildren(); without success
ftp.GoTo(path);
ArrayList listDir = null;
listDir = ftp.ListDir();
ArrayList listFiles = null;
listFiles = ftp.ListFiles();
DefaultMutableTreeNode child = null , dir = null , X = null;
//this will add files to tree
for (int i = 0; i < listFiles.size(); i++) {
child = new DefaultMutableTreeNode(listFiles.get(i));
if(listFiles.size() > 0)
model.insertNodeInto(child, chosen, 0);
}
//this will add dirs to list
for (int i = 0; i < listDir.size(); i++) {
X = new DirBranch("در حال دریافت اطلاعات ...").node();
dir = new DirBranch( (String) listDir.get(i)).node();
dir.add(X);
if(listDir.size() > 0)
model.insertNodeInto(dir, chosen, 0);
}
FilesTree.setModel(model); //this is my Swing JTree
}
the problem is every time i expand the JTree it duplicate list of files and folders. so i tried to use chosen.removeAllChildren(); # the top of the code but it didnt remove anything. what should i do?
Your model is correct, but JTree is operating on old information.
The removeAllChildren() method removes the children, but it does not fire any events and the model.insertNodeInto() does fire insert events. So, JTree sees the nodes being added, but never sees the nodes being removed.
After adding the new children, try calling model.reload(chosen) to invalidate the tree below chosen.
Since you will be reloading the branch, you can also change model.insertNodeInto(dir, chosen,0) to chosen.insert(dir,0). That reduces the number of events posted.
Calling removeAllChildren() will remove the children from the node. There must be something else happening here that is creating duplicates. Make sure you are not calling anything twice and that you are refreshing the display of the tree.
In my application also i just fact the same problem. For that i just used the following code.
JTree.removeAll();
JTree.setModel(null);
It remove all child nodes from my Jtree.

Categories

Resources