Replacing a running program with an fresh instance of itself - java

I am attempting to setup a reset method within a program that essentially creates a replacement of itself and then closes itself down leaving the replacement running. I know that normally to do this I could use some outside driver class and have no issue, but I am seeing if it is possible to create a completely independent instance of a class with itself.
If I create a new instance and then exit the existing instance, the newly created instance exits as well. I would imagine that this is possible but I can not find any way to go about it at this point.
The particular program I am working on is a Swing GUI and I have set the default close operation to EXIT_ON_CLOSE.
The reason that I wish to do this is that it would be more simple to just replace the current window with a new one than it would be to go all the way through and reset everything back to default.
Also on a purely theoretical note I would like to find out i this is possible.

Quick Solution: don't use EXIT_ON_CLOSE as your default window close option. Check the API and choose a better one such as JFrame.DISPOSE_ON_CLOSE.
You state:
The reason that I wish to do this is that it would be more simple to just replace the current window with a new one than it would be to go all the way through and reset everything back to default.
Which leads to a longer potential discussion: you probably don't want to do this, to exit one window and pop up another. Besides being annoying, there are probably much better ways to achieve this end. For one, your GUI should be based on a model, and resetting the model should be fairly easy if it is well written. If not, then consider refactoring it so it is easy. We can help you with this.

Related

Switching to fullscreen crashes application

Introduction
I’m attempting to switch my application from windowed to fullscreen. Earlier this would have been as easy as making use of LibGDX’s setDisplayMode(Display), as well as the same library’s getDesktopDisplayMode(). Unfortunately, some things have changed.
Research
As of LibGDX 1.8.0—inside the Graphics—what was previously known as setDisplayMode(DisplayMode) has been renamed to setFullScreenMode(DisplayMode), as well as what was previously known as getDesktopDisplayMode() has been renamed to getDisplayMode().
By then, one might think, that using the renamed methods in the same way as one previously would to switch from windowed to fullscreen would work just as fine:
// Tabulator key triggers change from windowed to fullscreen
// The application works fine until that of pressing the tabulator key
if(Gdx.input.isKeyJustPressed(Keys.TAB))
Gdx.graphics.setFullscreenMode(Gdx.graphics.getDisplayMode());
This doesn’t work fine by any means. As a matter of fact, the application hangs followed by crashing upon pressing the tabulator key.
It’s worth to notice that the setFullscreenMode(Display)—according to the documentation—returns a boolean depending on whether or not the operation was successful. In this case, if you were to put it inside a print statement, you can clearly tell it never returns: even should you let the application be for a while.
Moreover
I took a good look around the web—in vain—searching for possible causes of as to why this might be happening. Looking at the release notes of 1.8.0, it truly seems as though all that needs be done is switch from using the previous methods contained by the library to the new ones.
Question
Does anyone have any insight on as to why the application crashes upon pressing the tabulator key—granted the code following it as shown above is present? Perhas someone could at the very least point me in the right direction?
There’s a fair chance what I’ve concluded is missing out on some important facts.
Solution
It turns out I’ve managed to be slightly silly!
Background
Whenever I create applications—especially games—even though I use libraries such as LibGDX, I like to go ahead and create myself a separate thread for handling the game logic. This yields me more control over the application as a whole—whether it be tick extremely frequently whilst rendering more seldom, or the other way around.
By the way of my logic, the provided code from the question...
if(Gdx.input.isKeyJustPressed(Keys.TAB))
Gdx.graphics.setFullscreenMode(Gdx.graphics.getDisplayMode());
... I decided to put inside the tick method. Since that’s inside a separate thread, LibGDX probably felt a little left out.
Moreover
From my understanding, LibGDX handles all its logic inside the ApplicationAdapter’s render method. That’s where it evaluates all of the user’s actions and makes sure they don’t collide with other things taking place to its own various different components.
For the aforementioned reasons—when I decided to put the “fullscreen logic” inside a separate thread, LibGDX crashed. Oh well, at least it works now—That is, by putting the aforementioned code inside the LibGDX’s ApplicationHandler’s render method!

View all methods called during Runtime - Eclipse Java

I have a Java application and basically I want to know all the methods that are called in the background when I do something in the GUI. I know you can view the Call Hierarchy by selecting a method but that's while the code isn't running. I want to view every single method called in every class when I select something for example so I can figure out which methods/classes/packages are responsible for this functionality. I also don't want to have to set a breakpoint at the start of every method as there are far too many methods/classes/packages for that to be feasible. Bear in mind that I don't even know the first method called for some of the operations, if I knew that, it'd be easy to figure out what's going on.
Is there a way to do this or am I ahead of my time?
I think you could use the debug mode to see all methods called
Run DEBUG in your IDE, your each step in application will move you to the right place in the code, during your program you can see each variable value.
Also you can follow each code line which your code is doing.
http://www.vogella.com/tutorials/EclipseDebugging/article.html
Regards!

The "Date modified" field in JFileChooser is not updating when we select "Refresh" option

I was using JFileChooser for browsing the files. I have selected the view as "details".In detail mode the files are listed under four columns ie. Name, size,Item Type, Date modified. When I modify a file which the JFileChooser is currently showing and then if I right click and select the refresh option, the "Date modified" field does not get updated with the new time.
But when I go back to one folder level up and come back, the "Date modified" field will be updated with the new time.
What is the resolution to this problem??? Is it a bug???
I am using NetBeans 8.0 & its swing GUI Builder.
Please Help.
Thanks
EDIT: I removed the old answer because it is not correct.
Explanation
You mention you're using a GUI builder from NetBeans. Without seeing the code that was generated, I can only speculate at what is happening. To speculate, I would say that yes, the GUI builder from NetBeans is at fault for this - but then you might be at fault as well, depending on your perspective.
A good rule of thumb is never shalt thou ever use a GUI builder, especially in Swing. Code generation is a non-trivial task to begin with, but Swing is far more complex than most frameworks, and it makes Swing code generation that much worse. Essentially, you can look at a Swing GUI builder as a terrible entry-level developer, who will do whatever he can just to get it to work - no matter how unmaintainable or terrible the code is. The problem with this, is when something goes wrong (like it has for you), then not only do you have to know Swing to know what to look for, and you have to debug code you've never looked at before and likely will spend a great deal of time to understand, but now you the code you are trying to debug is terribly written at that. You really need to manually create your GUIs.
That being said, as I continue to speculate at what your problem is because you have no code posted, I'm guessing you tried to manipulate what the JFileChooser looks like...is this correct? If not, I suggest updating your question.
If it is the case, then that is your problem. It may seem obvious to you that the JFileChooser you are looking at in your UI is the JFileChooser that contains all the JComponents and Objects in the code. This is very wrong, unfortunately (did I mention Swing was complex?).
The JComponents you are looking at are actually part of your FileChooserUI object. If I'm not mistaken, the default FileChooserUI for any OS is javax.swing.plaf.metal.MetalFileChooserUI (it's at least the default for my local testing, and I don't think I've ever seen different for any other time I've used a JFileChooser). For your reference, here is an unmodified MetalFileChooserUI:
Now, I mention all this because it sounds like you modified how the JFileChooser looks by dragging and dropping things around. Since all the JComponents are actually housed in the FileChooserUI and not in the JFileChooser itself, what you actually did was modify the FileChooserUI. By doing this, I'm willing to bet that NetBeans created a new subclass of MetalFileChooserUI (or whatever FileChooserUI you are using). The way you might install a new UI to a JComponent would be by calling ComponentUI#installUI. There seems to be a flaw with this though. I haven't been able to figure out exactly how this flaw becomes a problem for the refresh, but I have my guesses. Either way, I will explain how this is a problem in the general way.
Basically, when you call installUI, it will make the UI that you are actually physically seeing look the way you told it to. However, the ComponentUI object has a reference to itself stored within the JFileChooser class and when you install the new UI, that old reference is not overridden with your new UI object. There seems to be some interaction between your JFileChooser object and the ComponentUI object when you attempt to refresh, and I believe that it is still calling the old ComponentUI reference when it needs to do any kind of update.
Solutions
There are two solutions here.
Solution 1
The first is to set the look and feel to the ComponentUI object you want before you ever create the JFileChooser using the UIManager#put(java.lang.Object, java.lang.Object), where the first parameter is the name of the UI you want changed (in this case it's 'FileChooserUI' and the second parameter is the string representation of the full classpath to the ComponentUI object you want to use. Before I go any further, let me say that I have not been able to get this to work properly, and my look and feel never seems to get used. What you're supposed to be able to do is the following:
UIManager.put("FileChooserUI", "com.my.classpath.to.MyNewFileChooserUI");
new JFileChooser().showDialog(null, "FOO");
and the JFileChooser will show up using the look and feel in com.my.classpath.to.MyNewFileChooserUI. The way this works, is when an JComponent is created, it goes to the UIManager and asks what look and feel it should use, and then instantiates the class it finds. You can read more about that in the JComponent documentation. As I said though, I have never been able to get that to work.
Solution 2
The solution I have gotten to work, is to do something a little hacky. Objectively, I don't even like this solution, and if Solution 1 worked, I would say absolutely don't do this. Since I can't figure out solution 1, I will tell you the only thing I know to work:
JFileChooser fc = new JFileChooser();
MyCustomFileChooserUI fcUI = new MyCustomFileChooserUI();
try{
Method method = JComponent.class.getDeclaredMethod("setUI", javax.swing.plaf.ComponentUI.class);
method.setAccessible(true);
method.invoke(fc, fcUI);
} catch (Exception ex) { /*catch whatever you want and handle it however you want*/ }
fc.showDialog(null, "FOO");
What's happening here, is that I'm calling a function that is protected. This function will install your ComponentUI for you, and also override the old ComponentUI reference inside the object. So, when the JFileChooser wants to access the look and feel by reference, it will now make sure it accesses the correct look and feel Object. This is what I was speculating the issue was; it was accessing the old ComponentUI reference when trying to 'refresh' the JList inside of the look and feel that displays the files.
Disclaimer
There are some things I didn't talk about here, like how to override the ComponentUI object, because I think that's a little out of scope. Also, this is a long detailed answer about something that I'm speculating, because you provided very few details in your question. Another rule of thumb for you: the fewer details you provide in a question, the less people will want to help you, and the people that do will likely give you an answer you weren't looking for because they don't know what you want.
Call the following instead of updateUI to refresh the JList in the JFileChooser:
((javax.swing.plaf.basic.BasicDirectoryModel)list.getModel()).fireContentsChanged();

Handling mouse input in a multi threaded game

First of all, I apologize for the unruliness of this question, I tried to explain everything that was essential without leaving anything important out or giving anything extra, but I may not have done the best job. I would post code but there is just way too much of it tot be able to post.
I am developing a game in Java, using no external libraries. I have a main class that also handles my Jframe. It sets everything up, such as size, title, etc, then starts a new Thread that handles everything else that's not basic setup. It's an loop that runs until the game is closed. It basically consists of update, then render. Those methods call the corresponding method in a state managing class, which contains an instance of a custom GUI class that I extend for all of my GUIs. I have it declared as a GUI rather than one of GUI's subclasses so that whenever I need to switch GUIs I can simply swap in a new one seamlessly. So the basic flow of the program is the threads update() -> state manager's update() -> GUI's update(), then the same thing for render. So my question is, since I have the Jframe declared outside of my thread, what is the best way to pass mouse input into the thread? If there was just a single object that I could grab and send into the GUI, it should be simple. But since there could potentially be multiple MouseEvents coming from the MouseAdapter between each frame, I can't seem to wrap my head around how to do this. The best idea I've come up with was to make an array of MouseEvents, then iterate through it in the update method. However, for some reason Eclipse kept giving me errors when. I tried to make the array, so I gave up on that in about a minute.

Correct way to use Actions to create menus, toolbars, and other components in Java

The naive way of writing building a menu in a Java Swing app is to do something like:
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open...");
openItem.addActionListener(new ActionListener() { /* action listener stuff */ } )
fileMenu.addMenuItem(openItem);
A more experienced developer will recognize that actions can be accessed through a variety of mechanisms - menus, toolbar buttons, maybe even other workflows in the system. That person is more likely to write:
Action openAction = new AbstractAction();
openAction.setName("Open...");
openAction.addActionListener(new ActionListener() { /* action listener stuff */ } )
...
JMenuItem openItem = new JMenuItem(openAction);
My question is, what is the best way to manage these Action objects so they can be used across menus, toolbars, etc?
Create a factory class that returns specific actions?
Declare all of the actions as private static final Action in some utility class?
Take advantage of a Java application framework?
Something else?
Applications that I have developed that need to use that same actions across menus, toolbars, and other buttons have been done using Swing Application Framework.
Swing Application Framework
This framework will allow you to have a resource file where you can define all menu text, tooltips, and ICONS. I think the icons are the key, you do not have to load them yourself. Also, if you have any actions that you need to enable/disable you can override the method to control its state.
The website is worth the read.
You can group all your abstractAction using the dedicated Map javax.swing.actionmap .
See http://java.sun.com/javase/6/docs/api/javax/swing/ActionMap.html
Moreover each JComponent has an internal actionMap (getActionMap()).
class MyComponent
extends JPanel
{
public static final String ACTION_NAME1="my.action.1";
public MyComponent()
{
AbstractAction action= new AbstractAction() { ... }
getActionMap().put(ACTION_NAME1,action);
...
menu.add(getActionMap().get(ACTION_NAME1));
}
}
Hope it helps
Action is a bad abstraction - an ActionListener welded to a poor man's Map.
Certainly do not assign them to a static as they are mutable and also need some context to operate usefully.
My general advice for GUI programming is to note that it is actually much the same as any other area of programming. Follow the usual good practices. Notably, layering, separation of concerns, use (implementation) inheritance rarely and don't write a big ball of mud.
Also see this question, which is pretty much the same as what you're asking.
Create a base action for your application; this will help you IMMENSELY later on
Do create actions as you have in your code, instead favor subclasses of your base action
To organize them, it will depend on what you are doing with them, and you may have some actions organized one way and others created a different way. It will all depend.
What you want is to have a consistent way to locate/create an action in your code.
Depending on your UI, you may need to differentiate between "static" actions (i.e. stuff that's always available in your app, such as the menu system) and dynamic actions that are created only on certain screens or in certain locations.
In any case, using concrete subclasses of your specialized base action will help you keep these things organized. What you don't want is to be specifying things like labels, mnemonics, and icons all over the place in your code.
Edit: I got the feeling people didn't believe this was possible or easy, so I did it--took about an hour from scratch--would have taken 40 mins if I'd just used a single method as a target instead of reflecting it out to separate methods for each menu item.
Here's the Tested source code. It works, but is one big method and ugly--refactor it if you use it. I may fix it up a little over the next few days, I've always wanted to have a copy of this to keep around to reuse.
--- original post
First of all, remember to separate your code from data. That means you should NEVER type:
new Menu("File...");
The string "File..." is data. If you start thinking this way, you will find that your question answers itself.
First you need to build up some data. You need to get "File..." and "Save" into menus. I generally start off with a string array (which you can easily move to a file)
new String[]{"File...","+Save","Load"...}
This is one of the simpler patterns I've started out with. Then you can parse out the + sign and use it to mean "Drop down a level in the menu when you add this one"
This is just a silly convention, invent your own if you don't like it.
The next step is binding that to code to run. You could have them all call the same method, but what a pain in the ass (Giant switch statement). One possibility is to use reflection to bind a method name while you are reading in the data. Here's one solution (again it might not fit your tastes)
new String[]{"File...[fileMenu]","+Save[saveMenu]","Load[loadMenu]"...}
Then you parse out the thing in square braces, reflectively hook it up to a method in your current class and you are set.
There is a temptation I ALWAYS have at this point, and I've learned to fight it because it NEVER works out. The temptation is to use the first set of data ("File...") and manipulate it to fit some pattern and auomatically bind to your code (in this case, remove all non-alpha chars, make the first letter lower case and append "Menu" to get the correct method name). Feel free to try this, it's very attractive and seems slick, but be ready to abandon it when it doesn't meet some need (such as two menu items with the exact same name in different sub-menus).
Another way would be if your language supports closures, then you could actually create the file name and closure in the same place..
Anyway, once you start coding like this, you'll find that ALL your menu construction is in a single 10 line method and you can alter it to suit your needs. I had a case where I had to change a set of menus to a button hierarchy and I did it in 2 minutes.
In the end, you can use this pattern to set up the action objects easily and change how they are used easily (in a single location, single line of code), so you experiment with them. There are many ways to use them, but if you don't do what I'm recommending here, you will end up having to re-implement across every menu item for every change, which is really annoying--after a single change you will have wasted more time than if you had just implemented a data-driven solution in the first place.
This really isn't hard code, should take like an hour or two then you never have to write new Menu("... again. Trust me, this kind of tooling is just about always worth it.
edit:
I just about always code data-driven these days. Usually I'll prototype a few things the normal way, recognize the pattern and refactor--and if you are refactoring correctly, the data just about always factors out and what you're left with is beautiful, tight and maintainable.
I could do what I suggested above in less than 1/2 an hour (maybe an hour to do the reflective version). This is almost always just as long as it would do to use the unfactored version, and from then on, your savings multiply for every change.
This is very similar to what people like about ruby, except with ruby they seem to insert even more data into their code (which makes it awfully hard to extract your data from the code completely, which is always a nice goal for internationalization).
Hmm, did I mention that if you're good at extracting your data like this, i18n is virtually free?
I suggest you just give it a try sometime and see what you think. Embedding the control in the strings is unnecessary if it makes you uncomfortable. I tend to use string/object arrays just because they are really easy to enter, are still in the file while you are coding and are trivial to externalize later, but if you like YML or XML or properties files, use whatever you're comfortable with--just abstract your data from your code!

Categories

Resources