Change class variables and save changes for future program runs? - java

For example, say I have:
public Class Foo {
public final int X = 1;
public getX() {
return this.X;
}
}
Is it possible to write something to change the value of X for future runs of the program? So if the value the user wanted to use for X changes, and all they have is a compiled .jar file, they could run said method and then the value of X in the compiled code would be forever changed.
I am developing software for a research lab, at which I work temporarily. What the lab techs will be interacting with is just a bunch of JFrames. They don't know how to change it in the code and then recompile, etc. So I am trying to find the best way to have a "Change Defaults" button which would open a window for them that they can edit the default values, click "Save," and then the new value is what is used until they change it again. How can I do this?

java.util.Preferences, designed for this purpose, but involves a little work

Related

'keyPress()' method for Robot object isn't typing anything

I'm trying to code a program in Java that automatically types each character in a string using the Robot class. I've used it to make a similar automated program a while ago (which I'll refer to as the 'previous project') that used 'keyPress()'. This and most, if not all, of the other methods for the Robot class which I needed to use worked perfectly.
Now I've started and 'keyPress()' isn't typing anything, regardless of the KeyEvent I pass as an argument. I thought I had written the code incorrectly, so I ran my previous project just to make sure it worked, but it didn't.
Here's the snippet of code I used for the previous project and my current one (which you can also use to test this).
EDIT: Try the on a text editor or anything that functions like a text field. I've now shown the entire demo class.
// demo procedure
public class DemoClass() {
public static void main(String[] args) {
new DemoClass().run()
}
public void run() {
try {
Robot robot = new Robot();
for (int i = 1; i <= 30; i++) {
robot.keyPress(KeyEvent.VK_A);
robot.delay(100);
System.out.println("Typed key");
}
} catch (AWTException e) {
e.printStackTrace();
}
}
}
'Typed key' gets printed 30 times and no errors appear in the output either.
I've tried;
adding 'robot.keyRelease(KeyEvent.VK_A)' just after the key press,
allowing the program type in the software I want to automate,
allowing the program to type in the IDE I'm using and in a text editor,
allowing the program to click in the IDE and text editor (so I could see if only pressing keys was the issue).
None of these have produced results. I've checked the code from multiple sources (articles and videos), all of which have the same code stub. I've read that some software prevent Robot objects from typing/clicking in them, but both typing and clicking worked when I was developing my previous project.
So I woke up today and... the program works.
I still don't know why it wasn't working in the first place or how the problem fixed itself (magic?). Running the sudo command didn't seem to make a difference, and none of the software I'm dealing with prevent a Robot object from automated typing/clicking.
It's most likely just a me-problem since other people managed to get it working. Since it's happened once it'll probably happen again.
Anyways, thanks to everyone that helped! If future readers have any ideas of why it didn't work then feel free to share them.

libGDX DragAndDropText.java is broken, looking for another example

I want to drag and drop TextButtons to designated targets. Searching this site, DragAndDropTest.java on libgdx's testing github is cited as an example to to start from. Implementing the flow described in the test, I received this error:
Exception in thread "main" java.lang.NullPointerException
at com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop$1.drag(DragAndDrop.java:111)
at com.badlogic.gdx.scenes.scene2d.utils.DragListener.touchDragged(DragListener.java:61)
at com.badlogic.gdx.scenes.scene2d.InputListener.handle(InputListener.java:62)
at com.badlogic.gdx.scenes.scene2d.Stage.touchDragged(Stage.java:315)
at com.badlogic.gdx.InputEventQueue.drain(InputEventQueue.java:89)
at com.badlogic.gdx.backends.lwjgl3.Lwjgl3Input.update(Lwjgl3Input.java:205)
at com.badlogic.gdx.backends.lwjgl3.Lwjgl3Window.update(Lwjgl3Window.java:390)
at com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application.loop(Lwjgl3Application.java:137)
at com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application.<init>(Lwjgl3Application.java:111)
at com.b2tclient.lwjgl3.Lwjgl3Launcher.createApplication(Lwjgl3Launcher.java:17)
at com.b2tclient.lwjgl3.Lwjgl3Launcher.main(Lwjgl3Launcher.java:12)
Eventually I just tried to run the DragAndDropTest.java directly and received the same error. Anything from a fixed test, pointing out where I may have gone wrong in trying to run the test, or a different working example of drag and drop to study would all be helpful in moving forward.
Note that I also tried a different path when I struck out here in implementing Lee Stemkoski's DragAndDropActor class. While that did work, the flow I learned from doing so is only good for his BaseActor family, and the work of re-implementing Buttons and such on top of it doesn't seem like the right solution. I'll take from that effort confirmation that drag and drop itself is not broken, just the test.
I've ripped out all of the dragging methods and tracking variables from Stemkoski's DragAndDropActor, and placed them in .addListener() for each item I want to drag within my screen. Now that I've seen my draggables moving around the screen without crashing, I think I'll make a new DragListener extending from InputListener, as that seems like the way to encapsulate the logic (open to feedback). Anyway, it occurs to me that the DragAndDrop class found in the DragAndDropText is never referenced in Stemkoski's work, so he must have implemented his own parallel drag and drop functionality. So I take back what I said about knowing the drag and drop that comes with native libgdx works, however unlikely it would seem that it not.
While this is technically an example of drag and drop that still works compared to the oft-cited test class, I think any answer provided that uses the vanilla libgdx packages should be considered a superior one.
I've done something like that :
public class DragAndDropActorListener extends DragListener {
private Actor actor;
public DragAndDropActorListener(Actor actor) {
this.actor = actor;
}
#Override
public void drag(InputEvent event, float x, float y, int pointer) {
this.actor.setY(event.getStageY());
this.actor.setX(event.getStageX());
super.drag(event, x, y, pointer);
}
}
With actor the object to move. you could also a little Offset for center the object on the mouse

Java in NetBeans - Adding actionEvents with custom parameters

I'm working on something in NetBeans, and I want to create an actionListener in a jTextPane for when the user presses Enter. However, I also need to input a String array (from a different subroutine within the source code) into the listener. But in NetBeans, events are generated automatically and I'm not allowed to edit this apparently extremely sensitive code. So, then, I tried typing up my own event thing (sorry about my terminology; I'm very new to GUI programming):
private void jTextPaneEnterPressed(KeyEvent evt, String[] stringArray)
{
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
{
// do something when the user presses enter that involves the program knowing what stringArray is
}
}
But when I run the program, pressing Enter in the text pane does nothing. I understand that this is because there is no actionListener associated with jTextPaneEnterPressed, but NetBeans gives no option for such customized code.
So what I want to know is either how I can pass in my own parameters when NetBeans creates an event handler, or how I can write my own actionListener alongside this actionPerformed block.
(And for the record, this is not an import problem)
I have tried looking this up, but have found nothing specific, as all other similar issues are not relevant to NB. Any help would be greatly appreciated.
*EDIT: This may seem like a trivial problem to most, but I'm open to any actual answers that tell me how to get done what I am trying to do, though I would prefer to stick with NetBeans. All I need is for the action listener to know that this string array exists, because the program needs to deal with that array when the user presses Enter. I'm sorry I can't give any specific context, but it's too much to get into.

Operation translation from jCombobox in Java to Spinner in Eclipse

Asking a follow-up question here after solving some other problems I was having.
Essentially, I'm translating a working program from Java into Eclipse for development of an android app. I've whittled down the problems to a single block of code. In Java, it looked like this:
private void shapeDropDownActionPerformed(java.awt.event.ActionEvent evt) {
if(shapeDropDown.getSelectedIndex()==1)
diameterBox.setText("0");
if(shapeDropDown.getSelectedIndex()==1)
diameterBox.setEditable(false);
if(shapeDropDown.getSelectedIndex()==2)
widthBox.setText("0");
if(shapeDropDown.getSelectedIndex()==2)
widthBox.setEditable(false);
if(shapeDropDown.getSelectedIndex()==2)
heightBox.setText("0");
if(shapeDropDown.getSelectedIndex()==2)
heightBox.setEditable(false);}
Basically, if the user chooses a rectangle over a cylinder, the diameter input is set to "0" (so it is an integer) and is set to not editable. Or, if the user chooses cylinder, the height & width inputs were set to "0" and not editable.
However, I'm having difficulty with this method in Eclipse. Could you please show me how to implement this method in Eclipse? This is what I've got so far that is not working, thus making the entire app malfunction:
//Blank out the appropriate blanks:
private void setOnItemSelectedListener (new onItemSelectedListener() {
if (shapeDD.equals("Rectangle"))
txtDiameter.setText("0");
if (shapeDD.equals("Rectangle"))
txtDiameter.setEnabled(false);
if (shapeDD.equals("Cylinder"))
txtWidth.setEnabled(false);
if (shapeDD.equals("Cylinder"))
txtWidth.setText("0");
if (shapeDD.equals("Cylinder"))
txtHeight.setEnabled(false);
if (shapeDD.equals("Cylinder"))
txtHeight.setEnabled(false);
});
A secondary issue I'm having is with resetting the spinner once I'm done with it. In Java, it's simply:
jCombobox.setSelectedIndex(0).
What is the equivalent method in Eclipse for a Spinner?
I can answer to your second question: the equivalent method for the spinner is setSelection(index), for references see http://developer.android.com/reference/android/widget/AbsSpinner.html#setSelection(int)

Switching from GUI to Command Prompt in Java?

My professor assigned a project where a simulation is ran through a GUI. To edit it, we need to create a "New" menu item. We haven't learned how to get data from a GUI, and our book does not cover it at all.
What I'm trying to do, is when the "New" command is hit, focus gets shifted back to the CMD prompt, where System.out. starts working again and prompts the user for input.
However, when I try to implement this, my program crashes. What can I do to solve this problem?
It doesn't look like you're keeping the reference to your newly created GUI. As far as I remember, Java will garbage collect the FoxGui object (as well as any other object) if there are no references to that object. Try creating a global variable to store the reference to your newly created FoxGui object. Something like...
FoxGui MyGUIRef;
public void actionPerformed(ActionEvent event)
{
System.out.println("Item: " + event.getActionCommand());
// File Menu Controls
if (event.getActionCommand().equals("New"))
{
MyGUIRef = runNew();
}
}
//Now returns a reference to FoxGui
private FoxGui runNew()
{
return new FoxGui(....)
}
Is the System.out in a terminal (non Java) window? If so, I think this would be much harder than you'd think.
I'd be tempted to redirect the System.in / System.out to a JTextPane on the GUI (That way, it would be much easier to change the focus etc. I think you need to try and explain what you're doing a little better in your question and perhaps post a stack trace when your program crashes.
Anyway, to do something when the "new" menu item is clicked you'd need to do:
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Code here to be performed when the item is clicked
}
});
You know what? I found a real simple solution, JOptionPane. I just needed to find a good example. It'll work fine for what I want. Thanks for all the help. I'll checkmark everyone who helped.
I know that it is very late answer, but anywhere...
There is only one way to do exactly what you want.
First you need to remember to run you project from CMD by java -jar jarname.jar
Catch click action and perform system.in
Information:
It is the only solution, because GUI never give focus to CMD, but if GUI runned from CMD you can use easily System.in.
Regards, Greg

Categories