Keep track of Swing GUI "current state" - java

Sorry the title is fuzzy, but I really coudln't come up with a fitting title.
I'm developing my first application with Swing, and I'm having a hard time figuring out how to keep track of the current view of the application. With I mean with current view is for example if a button has already been pushed. For example, you shouldn't be able to press "Execute" before a file has even been loaded. I've come up with an architechtural solution to this that is really crappy, and I'd like tips on how to improve it.
I have a label called infoText, and it's updated pretty much every time I press a button. Through this, I'm keeping track of the applications state in this fugly way:
if (infoText == LOADING_NARROW){
printSelected(narrow_list);
}else{
printSelected(list);
}

Rather than keeping track of your state with GUI components, use normal Java objects and variables.
Just keep a boolean loadingNarrow in this case that you reference and update when needed.
Also if you are running a large load as the result of a button press and don't want the user to press it again you can disable the button once the load starts and re-enable it later. (Note I am assuming you are running the load on a separate thread so the GUI does not freeze).

Swing Components keep track of their own states.
My advice:
Initiate the application to a default state.
Adjust the settings in an event driven manner. For instance when JButton A is clicked, enable JButtons B and C and set a JTextField.
Check the states of objects with their builtin methods. Example
if((jButtonA.isEnabled() && jTextField.getText().equals("foobar"))
You can also use the mediator pattern to group related components and their actions.

First: Are they different methods, or a copy-paste-error?
printSelecteds (narrow_list);
printSelected (list);
Second: To disable a button you usually use:
ok.setEnabled (false);
If the file is loaded, you call
ok.setEnabled (true);
to enable the JButton "ok".
I don't see how that is related to your info-text, and to your printSelected(s) method. If you pass the state via the GUI, you might loose the one or the other due to race conditions. Changing a label could be the sink of an state change.
You could have mutual exclusive bit patterns to allow interference:
FILE_OPEN = 1;
SEARCHED = 2;
FRIDAY = 4;
to add them bitwise:
state |= FRIDAY
to ask them up in a binary pattern:
if (state | FILE_OPEN) ....
It doesn't look very elegant to me. I guess I'm not sure what your problem is. :)
To fire an action if some button is pressed, you have to implement an actionListener, which could modify your label as well. But the swing eventloop will already check the state of your components. You seem to duplicate the work partly.

Related

Advantages of InteractionDialog over Dialog?

I was recommended to use InteractionDialog rather than Dialog, but I'm failing to see the advantages. What I can see is a problem. What I need is letting the user enter a PIN or whatever and wait for their answer. This is needed both on the EDT thread (the user choose to save the PIN) and on other threads (a web page requires the PIN for login).
With Dialog,
I can call it from the EDT thread and it works nice.
When on a different thread, I can be trivially adapted by a one-liner in the callee (see getFromGui in my linked question).
With InteractionDialog,
I can use it easily from other threads via some simple wait/notifyAll magic.
I can't use it from the EDT thread, except via callbacks like okBtn.addActionListener(...), which is verbose and ugly.
So I am confused and asking:
What do I gain from the InteractionDialog?
Is there a simple way how to use it uniformly no matter what thread I am on?
There are two separate things here:
Modality
How it works
A dialog can be modal or non-modal but it isn't interactive like an InteractionDialog. The modal dialog blocks the EDT internally using InvokeAndBlock so the current thread stops until there's a response from the dialog. This is convenient but has some edge case issues. E.g. the event that launched the dialog might trigger other events that would happen after the dialog was dismissed and cause odd behavior.
But that's not the big thing in modality. Modality effectively means the form behind you "doesn't exist". Everything that matters is the content of the dialog and until that is finished we don't care about the form behind. This core idea meant that a dialog effectively derives form and as such it behaves exactly like showing another form effectively disabling the current form. What you see behind the dialog is a drawing of the previous form, not the actual form.
Text fields can pose a problem. Because the way the dialog is positioned (effectively padded into place within its form using margin) the UI can't be scrolled as text field requires when the virtual keyboard rises. Since people use dialogs in such scenarios we try to workaround most of these problems but sometimes it's very hard e.g. if the dialog has a lot of top margin, the virtual keyboard is open and covering it. Or if the user rotates the screen at which point the margin positioning the dialog becomes invalid.
Note that in InteractionDialog Some of these issues such as the margin to position also apply.
Now InteractionDialog is a completely different beast that sprung out of a completely different use case. What if we want a dialog such as a "color palette that floats on top of the ui?
We can move it from one place to another but still interact with the underlying form. That's the core use case for InteractionDialog. As such modality is no longer something we need so it was never baked into InteractionDialog although it technically could have been (but it doesn't make sense to the core use case).
It's implemented as a Container placed into the layered pane of the current form so the form around it is real. Because the form is "live" layout works better and the removal of modality makes some edge cases related to editing slightly better. There are still some inherent problems with dialog positioning and rotation though. It also allows you to click outside of the dialog while input is ongoing which might be a desirable/undesirable effect for your use case.
Overall I try to use dialogs only for very simple cases and avoid input when possible. If I use input I never use more than one field (e.g. no-username and password fields) so I won't need to scroll. These things work badly for native UIs as well e.g. with the virtual keyboard obscuring the submit button etc. Since those behaviors are very hard to get right for all resolution/virtual keyboard scenarios.
Based on the answer from Shai, I wrote a form working as the base class for most of my dialogs. Basically, it shows the content from the subclass and adds the "OK" and "Cancel" buttons.
There's a method for use from the EDT thread like
public void showAndThen(BooleanConsumer consumer) {
assert CN.isEdt();
...
okBtn.addActionListener(a -> {
lastForm.show();
consumer.accept(true);
});
cancelBtn.addActionListener(a -> {
lastForm.showBack();
consumer.accept(false);
});
}
where BooleanConsumer is a trivial void accept(boolean b) interface.
There's another method for use from other threads
#Override public final boolean ask() {
assert !CN.isEdt();
final BooleanTransfer transfer = new BooleanTransfer();
CN.callSerially(() -> showAndThen(result -> transfer.set(result)));
return transfer.await();
}
where BooleanTransfer is a two-method class where the thread calling set passes a boolean to the thread calling await.

Same Jbutton selected state across multiple instances of same JPanel?

I have a toggle JButton that, when clicked, either installs or uninstalls some listeners elsewhere (but that's somewhat irrelevant I believe, as it could be just about any code that you don't want executed any number of times in a row, hence, the toggle, you click it once, it does something, you click it again, it undoes that something or whatever). My problem is that I have several instances of this button (or more specifically, several instances of its parent JPanel). This restriction is not my doing and I cannot prevent this. Basically, I'm left with a situation where the user can toggle the button "on" a bunch of times in succession, and needless to say, this screws things up for me.
The buttons themselves are not all visible to the user at once, only one can be seen at any given time. I tried using a component listener, but componentHidden() and componentShown() are never called.
I tried making the button a singleton, but that just had this weird effect of only displaying the button on the last panel it was added to.
I'm kinda stumped. The behaviour I want is simple: Multiple instances of this toggle button that sync their selected state. Ideas?
P.S. I suppose I could construct a list of the instances and update all the other's state when one of them is clicked, but I wonder if there's something simpler out there.
Thanks
Yes, the buttons must all be distinct, but they can either share the same ButtonModel or the same Action. Usually, I try to have them share Actions by creating a single Action that extends AbstractAction, and use it to set the Actions of all the same buttons.
No big reveal here. I solved my problem using my own suggestion, that is, I simply kept a list of all the instances of the button and set their states when any one of them was clicked in an action they all share.

How do JButtons in advanced applications work?

How do buttons in software written in Java work?
For example the above screenshot: when the user clicks different buttons, different algorithms are run on user-inputted data (it's a data analysis application) and the output is displayed. Just getting started writing Java GUI's though, it all seems like magic to me -- is there one ActionListener for every pane? Does it listen for different ActionCommands of the different buttons and execute the algorithm right within the actionPerformed() method (it seems a little nonintuitive to me to execute an algorithm in a method independent of data...i.e. the button doesn't know what data it's dealing with?). So far, all the action listener tutorials I've read online have merely printed something when the button is pressed...
What's the general structure for connecting button, actionlisteners, and actual actions performed in the background?
Thanks in advance.
The usual way is to have one action listener per button. The Statistics panel has access (via one of its fields), to the data it needs to read and modify). So, the handling of the first button in this panel could look like:
private void initButtonListeners() {
this.averageDegreeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
computeAverageDegree();
}
}
// other buttons...
}
And the computeAverageDegree() method could look like
private void computeAverageDegree() {
double result = this.statistics.computeAverageDegree();
this.averageDegreeLabel.setText(formatDoubleToString(result));
}
My personal preference is to do almost nothing in the UI, but move it all to the model/controller side (not sure what the best name is as it is seldom pure MVC).
I think that everything you do in the UI should be doable through the API as well. Benefits are easier testing, redesign of the UI is possible without messing up your logic, easy to perform the heavy work on background threads, ... .
A good read describing this is the Humble Dialog article. Not really Swing specific, but applicable to all sort of UI's.
To answer your questions:
is there one ActionListener for every pane?
No, typically you have an Action (or ActionListener) for each button. I prefer to use Action instances as they are far more reusable then the typical anonymous ActionListener (and easier to test as well)
Does it listen for different ActionCommands of the different buttons and execute the algorithm right within the actionPerformed() method
Certainly not. Doing heavy calculations in that method will block the Swing UI thread (the Event Dispatch Thread), which results in a non-responsive UI while the calculations are ongoing. Showing progress becomes also impossible. Calculations are typically done on a worker thread, launched when your Action is triggered (for example using a SwingWorker). This is explained in the Concurrency in Swing tutorial.
it seems a little nonintuitive to me to execute an algorithm in a method independent of data...i.e. the button doesn't know what data it's dealing with?
The button should not know about the data. The data is typically stored in the model. The UI is only displaying it, but does not contain it (unless it is input just provided by the user). The button should just know what to call on the model. The model does whatever it has to do and fires an event. The UI picks up that event and updates itself.
At least, that is how Swing is designed (for example JTable and its TableModel). I so no good reason to not follow that model when making your own Swing UI's

How do I revert state of JToggleButton from another class?

I am trying to write simple vector graphics editor in Java and got stuck with GUI... I have 2 JPanels: First one is for the "canvas area", second one is for the buttons. Canvas area is a Singleton, so then button pressed, it calls method of the Singleton and it adds element to list of the Singleton and re-paints the area. But now, I want to change these buttons to JToggleButtons and don't know how to revert it's state after click on the canvas.
Which design pattern should I use (because I have bad feeling that I'm doing it wrong)?
Have you ever heard of call backs? Once they are understood and implemented correctly, they can work quite nicely.
http://en.wikipedia.org/wiki/Callback_(computer_science)
I like this example too.
http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ310_019.htm
Make use of the Command and Memento patterns. Implement an Undo Command. Allow commands to store state in the form of a Memento. Restore the state from the Caretaker when you find fit.

toggle button vs image changing button

When to use this functionality and when to use the other? I personally thing that to switch between two different modes one should use a toggle button but i need to convince some people at work. any formal UI literature on the subject? thanks
I don't have references for you, but as a user I can tell you what I would expect.
I would expect the button to change images when you substitute one action for another because you entered a different mode. This is really relevant to save real estate in your toolbars, etc. For example you could have a dedicated play button and stop button with one always being disabled. Using one button saves space since at no point will both be enabled.
I would expect a normal depressed/unpressed toggle button when there is one mode that you either enable or disable. An example of this is "Toggle Mark Occurrences" in Eclipse. Unpressing that toggle button does not constitute a new action, but rather disabling an active mode.
I’m inclined to go with toggling buttons (buttons that “stick” depressed when “on”) rather than swapping images or label for a command button. I can’t cite any formal literature, but my impression is that it makes it easier both to anticipate the action produced by activation and to read the current state. The appearance and behavior of a toggle button is consistent with physical toggle button switches (like the Play buttons on older physical tape recorders). It’s also consistent with option buttons, check boxes, and state menu items, which all indicate their affirmative states through peripheral graphic design rather than labels. When the control looks like a command button (raised appearance), it’s labeled like a command button, the label indicating the action committed like any command button (e.g., “Connect”). When it looks like a state indicator (sunken, like a text box), its labeled suggest its current state (connected).
A single toggle button should only be used when there are simple True and False states to the process (e.g., Connected or not). Otherwise you need two or more “segmented controls” (abutting toggling buttons) to ambiguously indicate the alternatives (e.g., Forward vs. Reverse). This is analogous to using two option buttons in place of a check box.
Swapping labels to indicate changes in a button’s action can work if you use text labels that unambiguously indicate the action committed on activation, e.g., (“Connect” and “Disconnect”). While the Play/Pause button is a defacto standard, I’d otherwise avoid using an icon or image because it may confuse users on whether the label is indicating the current state or the state they’d get on activation (i.e., the opposite). There have been buttons that do one or the other, so the user can’t rely on experience. An image it not clearly a verb or adjective, so labeling with an image is tantamount to using text labels like “Online” and “Offline.” Even if done right, swapping labels has the disadvantage that the user needs to do a weird mental transformation to read the affirmative state (“It says I can disconnect, therefore I must be online now”). It can also mean you need a wordier label.

Categories

Resources