Assistance needed with Java GUI working with ODFDOM - java

Ok, so as a little personal programming project I had been trying to make a program in the past which would (via a GUI) held to record data of item drops from certain stuff in a game (Guild Wars 2 if you're curious). The GUI is simple enough: JFrame containing two JLabels and JTextFields, to say what to input and well, the text fields to type it in. Basic GUI stuff. The inputs are the item name and the amount. Also, there are two JButtons, with a listener each to add items and subtract items and finally another JLabel to function as error message display.
The structure of the "mapping" of items to amount obtained is stored during the execution of the java program in a TreeMap.
I had been creating a crude, basic implemention, saving data to memory in a .csv file but I decided last night I wanted to rework the system. Thus, I got the idea of trying to "write" to a spreadsheet format, and I thought, "well why not OpenOffice? Consequently, I discovered the ODFToolkit API and such, specifically the ODFDOM tools have been of interest to me of course. So I had thought I had this stuff refactored (if that's the right term) well enough and that things would go smoothly but...here's my problem:
So, in the GUI I type some test input; "Rotten Egg" is a valid item (invalids make an error display in the window) and I put some positive integer (only possibly type of valid "amount") for the amount obtained. Now, the first time I do this, with a valid input like this it works fine, but if I try again with different input or the same it displays the error text that should show only when an invalid item is entered. I tried a few things at least to debug it looking through it, but I am at a loss as to how this horrible bug has been created.
I will link to pastebin for my own two classes here:
GUI class: http://pastebin.com/rEbFS27j
Other class i.e. the Map structure and other stuff going on "behind" the GUI: http://pastebin.com/BWA4SUY0

sigh I figured it out eventually. I have this loop in the method that writes to the spreadsheet.
while (it.hasNext() == true) {
Map.Entry pairs = (Map.Entry)it.next();
odt.getTableList().get(0).getCellByPosition("A" + i).setDisplayText((String) pairs.getKey()) ;
odt.getTableList().get(0).getCellByPosition("B" + i).setDisplayText((pairs.getValue().toString())) ;
it.remove(); // avoids a ConcurrentModificationException
i++ ;
}
The line it.remove() ("it" is an Iterator variable) is a fatal error...an unfortunate remnant from a copy-paste when I looked up stuff in the past about how to use iterators... :/ Indeed it was the cause of this horrid "only works once" kind of bug. Guess I just really need to make sure I'm not using something wrong or unnecessary when I paste snippets of someone else's code into my work...

Related

Can you change a line after you've outputted it with System.out.println?

I have been coding for a while now and as far as I'm aware, once you've outputted a line to System.out.println in Java; you cannot change it.
The reason I ask this question is because of some very strange results from my program. The program records the time of the bubble sort and merge sort algorithms in sorting different kinds of int arrays and prints the average of these times at different sizes of n, where n is the size of the array.
Now I've had a litany of problems with this program thus far, but I do not understand how the following is possible:
...
At 200000, randomly-sorted takes:
NaN //Expected output, since I did not activate the random arrays.
...
However, at the same line, and in an unpredictable manner, the program occasionally does this:
...
At 200000, randomly-sorted takes:
75683.45
...
And then swaps back again after a while!
So the program is somehow managing to replace the outputted line, which I have never experienced before.
Any help or clarification very much appreciated! If you need the code, I am more than happy to share.
EDIT: To clarify, this is on a Macbook Air running Java SE 6. As for the code, please refer to my Github account with the entire project at the following link - https://github.com/danielsoutar/complexityPractical.
Side-note: One other thing. For bubble sort, the randomly-generated arrays apparently take longer to sort than a reverse-sorted array, which is clearly nonsense. Not sure if that matters to this problem but it is something to note.
the question was kinda unclear to me, but as far as I understand you could take a look at RegEx for filtering out on a String or clear the Console and put your output back in.
Clear console:
Runtime.getRuntime().exec("cls");
RegEx example:
yourString.replaceAll("[yourCharactersToReplace]","");
System.out refers to a PrintStream instance. In the abstract, a PrintStream object represents a place where you can send text. Period. Once the text is sent, that's the end of the story.
But in reality the text actually goes somewhere. If you are invoking your Java program from a command line, then it's very likely that the place where the text goes is a terminal emulator window or a console window; and it's also very likely that the console recognizes certain codes that your program can embed in the text that tell it to do things.
Things like, change the color of the text, move the cursor around in the window, and over-write text that already was there.
There have been literally hundreds of different coding systems to let a computer program do those things on a terminal screen/window, but one is supported by almost all consoles and terminal emulators. Google for "ANSI escape codes" to learn more about it.
If you want your program to purposefully move the cursor around, change the text color, etc. Then you might want to use a 3rd party library like jcurses (google for that too) to handle the possibility of a console that does not accept (or is not configured to accept) ANSI escape codes.

how to record keystrokes in background using java?

I am going to research on which key typed most in which hour in a 24-hour-day?
Later, I would research on which word used most in which hour in a 24-hour-day?
Say in the evening you would find most used word good or bye as people usually ends up their meeting in the evening.
So, I need to record keystrokes on the background using a java application with a time-stamp.
My questions are:
How to run a java program on the background?(Obviously informing the user).
How to record keystrokes which are used in other applications and counted in the java application without affecting its original application?
Note that:
This question does not serve my problem. Though it has an accepted answer, but the answer is not helpful for me because it could not distinguish between uppercase and lowercase letter, it returns same ASCII character. It just gave some sources and some other files. I expect more readable answer and a clear view how the java program launch on the start up and run on the background.
Just a little information to get you moving in the right direction. What you are looking to implement to listen for the keystrokes is KeyListener. I believe the actual function is keyTyped(ActionEvent e) but am not sure.
Other then that to run a program silently in the background will probably require some manipulation of the window + windows properties. You could just have the program run without a UI, or create a very lightweight UI that posts data. If you are looking for an actual "out of sight out of mind" background process, I am not sure how to do this with Java. However I imagine just an un-intrusive GUI would be sufficient for your purposes.

Organizing many texts by swapping instances

I am planning to develop an adventure-like game.
For that I am going to have a lot of instances of classes with different texts (basicly strings).
I dont want to hardcode this many texts, so i am looking for a way to do it better.
The guy in this video ( https://www.youtube.com/watch?v=8CDePunJlck ) is using json to write text files for each class instance manually and parse them automatically into instances. That goes into the right direction.
I´m looking for more information on that, so how is this procedure called?
Its said in the video that this also works with databases?
Is there a way to design a little bit more complex stuff with things like this?
E.g. I have the case that I would like to output different texts if e.g. a local or global variable is over a treshold etc. Can I do this without hardcoding and write an own class for each of my proposed instances?
Thank you!
Your question is quite broad, and it is hard to give a definitive answer. Here are some thoughts - hope you find it helpful.
You are right that you don't want to hardcode strings. The alternative to this is storing strings as external resources, and loading them into your game at start. There are numerous ways the resource can be organized; the choice depends on your programming platform, game architecture etc. For example, you can use simple name-value approach:
AREA_1_DESCRIPTION: You stand next o a small white house.
ITEM_22_DESTRUCTION: The nasty snake disappears with a loud "Bang!"
Using JSON or XML will give you more structured storage, which can be of great help, since you can organize your texts so that it is easier to use them in the code:
<item id="375" name="Great Sword">
<short_description>A Great Sword of Darkness</short_description>
<long_description>The sword has almost black blade with some unknown runes engraved</long_description>
</item>
If your programming system can access a database, then you can do something similar and store texts in the tables; this, however, might make it more difficult to edit texts later. If you want to go this way, I would still recommend using XML or JSON to store the texts, and making the game import texts in DB on the first run.
You probably will also need some sort of simple template-handling engine to be able to re-use some strings. You can start with creating your version of Java String.format() method. Your method might take as a first argument an ID of a string in your string catalog, and use some simple placeholders for the parameters. Suppose you have the following entry in your catalog:
FIRE_GEM_ACTION: "The Fire Gem touches %% and in %% seconds it turns into ashes."
Then you can write a method that will do something like this:
int delaySeconds = 5;
String message = MyTemplateProcessor.process(FIRE_GEM_ACTION, "old map", delaySeconds);
The function will take the string from the catalog, search for the occurrences of the placeholders (%%) and replace them sequentially with the parameters, so in the message you will get: The Fire Gem touches old map and in 5 seconds it turns into ashes.
In general, I would recommend you to have a look at some systems specially designed for creation of adventure games. Inform 7 will be a good starting place: http://inform7.com/learn/

Methods of Data Storage - Opinion

I have been working on an app and have encountered some limitations relating to my lack of experience in Java IO and data persistence. Basically I need to store information on a few Spinner objects. So far I have saved information on each Spinner into a text file using the format of:
//Blank Line
Name //the first drop-down entry of the spinner
Type //an enum value
Entries //a semicolon-separated list of the drop-down entry String values
//Blank line
And then, assuming this rigid syntax is followed always, I've extracted this information from the saved .txt whenever the app is started. But things such as editing these entries and working with certain aspects of the Scanner have been an absolute nightmare. If anything is off by even one line or space of blankness BAM! everything is ruined. There must be a better way to store information for easy access, something with some search-eability, something that won't be erased the moment the app closes and that isn't completely laxed in its layout to the extent that the most minor of changes destroys everything.
Any recommendations for how to save a simple String, a simple int, and an array of String outside the app? I am looking for a recommendation from an experienced developer here. I have seen the storage options, but am unsure which would be best for just a few simple things. Everything I need could be represented in a 3 X n table wherein n is the number of spinners.
Since your requirements are so minimal, I think the shared preferences approach is probably the best option. If your requirements were more complicated, then a using a database would start to make more sense.
Using shared preferences for simple data like yours really is as simple as the example shown on the storage options page.

Need help creating a Quiz App for Android w. HashMaps & No Database

My assignment is to create a simple Quiz app for Android. I am NOT looking for the code for this.. I am simply looking for someone to possibly lay out how to get started with this (pseudo-code ish).
The program is suppose to display one term and four definitions; one of them being the correct one. Once the user selects which one they think it is, the program will tell the user if it was correct / incorrect using a toast message.
Specs:
The terms need to be randomly selected, and only displayed once per run. However the definition needs to stay in the pool of definitions for other questions.
Definitions randomally selected (except the right one)
Program ends if it runs out of terms to display
Needs to use an ArrayList to hold collections of items, and a HashMap to hold name-value pairs.
Must use Androids logging mechanism to log error messages (via try/catch statements).
If you can help me out by guiding me in the right direction, that would be great :) Thanks!
I would (as always in object-oriented languages) start by mapping your problem to real-live objects. In your case, there would be two:
A Question-class which holds four answers, the question and offers a method to check if the given answer was correct.
An Answer-class which holds a single answer and whether it's correct or not.
As for your storage question, I wouldn't use a HashMap at all. Store the Question-instances in an ArrayList and use a Random.nextInt()-method to get a random question from your list.
In your Question-class, you would store all possible answers in another ArrayList. To randomize the order in which the answers are presented, you can use the Collections.shuffle()-method.
For the presenting part, have your Question-class return the question (string) and the four answers (strings) and put the into your widgets. To identify the answer given, you can use the Answer-instance (using the array-index is easier, but it is more error prone).
To check if the right answer was given, query your Question-classes isCorrect(Answer)-method and check if the given instance in the internal ArrayList is marked as the correct one.

Categories