Swing JTabbedPane : addChangeListener or addContainerListener or both? - swing

I have one swing code written by other person. For swing tabbed pane, he has added both change and container listener and both calls the same method:
addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent theEvent ) {
someMethod();
}
} );
addContainerListener(new ContainerAdapter() {
public void componentAdded(ContainerEvent theEvent) {
someMethod();
}
public void componentRemoved(ContainerEvent theEvent) {
someMethod();
}
} );
Whenever tab is removed from this tabbed pane, it internally calls JTabbedPane.removeTabAt(int index), which in turn calls fireStateChanged() causing new change event listened by change listener.
Now as new component (tab) is removed from tabbed pane, it also calls componentRemoved(ContainerEvent theEvent) method of container listener.
Both change even and container events, then calls same method someMethod(), which does set background and foreground colors.
I would like to know, if this kind code might cause some issues. Recently we are facing random IndexOutOfBoundException exeptions. I am just wondering, if this is causing this issue.
Also as per my understanding in swing, once event is listened, logic inside it should be executed using worker thread (e.g. SwingWorker). Please let me know if this is correct.
I am new to swing, thus any hint would be appreciated.
Thanks.

Whenever tab is removed from this tabbed pane, it internally calls
JTabbedPane.removeTabAt(int index), which in turn calls
fireStateChanged() causing new change event listened by change
listener.
This is true if the removed tab is also the selected tab. In the other cases, you won't be notified.
You need to choose what event you want to listen to:
Addition/Removal of components?--> go for ContainerListener
Selected tab? --> go for ChangeListener
I would like to know, if this kind code might cause some issues.
Recently we are facing random IndexOutOfBoundException exeptions. I am
just wondering, if this is causing this issue.
Since there is no line in your sample code that could throw that Exception, it is impossible to answer your question. Post an SSCCE that shows your issue.
Also as per my understanding in swing, once event is listened, logic
inside it should be executed using worker thread (e.g. SwingWorker).
Please let me know if this is correct.
It depends:
If you need to modify anything in the UI, anything related to Swing, it needs to be executed on the EDT (Event Dispatching Thread) and thus, SwingWorker is not an option.
If you need to perform business logic operations, and especially if they can be lengthy, then you should indeed use a SwingWorker or any other mechanism to execute that code in another thread than the EDT. Consider visiting the Swing tag wiki on "Concurrency"

Related

How do I programmatically play a button animation?

How do I make it look like a button was pressed using C# code? If I can actually push the button (play the animation and activate the events associated with the button press) with code that would be even better.
Playing the animation is pretty easy, using the Visual State Manager:
private async void PretendToClickButton()
{
VisualStateManager.GoToState(myButton, "Pressed", true);
await Task.Delay(250);
VisualStateManager.GoToState(myButton, "Normal", true);
}
You can play with the delay as you see fit.
Programmatically raising the event is not possible; you just have to call the handler method(s) directly (which assumes you the code that handles the event).
[Edit: You could subclass Button and provide your own mechanism for simulating the Click event, but that makes the XAML a wee bit trickier]

Pause UI in WinRT 8.1

I can't for the life of me get the following functionality to work:
User taps item
Item's image becomes visible via changing visibility property of image
After a short period of time image becomes invisible again (with no user input) via changing the
visibility property
Or, more simply:
Make visible UI change
Pause so user can see UI change
Reverse step 1's UI change
Step 2 happens before steps 1 and 3 regardless of where the code is because the UI is not updating until the logic finishes (I assume).
I am setting the visibility of the image via data binding with INotifyPropertyChanged. All works as expected except when I'm trying to introduce the pause.
I'm trying to pause with this simple method:
private void Pause()
{
new System.Threading.ManualResetEvent(false).WaitOne(1000);
}
It does pause, but the UI changes wait until after that pause even though a change to the bound data happen befores the pause is called, and the other change after.
I have tried using the dispatcher, but it doesn't change anything, and I don't understand it enough:
await dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
{
clickedCard.IsFaceDown = false; // makes the image visible via data binding
}
);
Pause();
I think I need to do something with threading, but I am going in circles.
Any ideas?
You should never do something like this inside the UI thread of your app:
new System.Threading.ManualResetEvent(false).WaitOne(1000);
There are various reasons for not doing it, but in your particular case the problem is that XAML only re-draws once your event-handler completes. So basically this happens:
The item is invisible
Your event handler is called
You set it to visible (but the UI doesn't refresh yet)
You freeze the thread for a second
You set it to invisible again
The event-handler completes
Now the UI updates based on the current value (which is invisible)
I suggest you look at building a Storyboard to do this - Blend can help. See here.

Page constructor called multiple times - Windows Phone 8

I have a page in a WP8 application, that every time I navigate to it, the constructor is called.
From what I know, the constructor of a page called only once at the first time the page loaded. my page is very heavy, and every construction takes wasted time..
this my navigation code, usual one:
NavigationService.Navigate(new Uri("/Views/Pages/ContentControlNew.xaml", UriKind.Relative));
and this is the constructor of the page:
public ContentControlNew()
{
InitializeComponent();
}
Not special.. is it normal that the constructor is called every time? Please tell me if you need more details because I don't know what else to say about this subject.
Yes this is normal because whenever you use NavigationService.Navigate it always creates a new page object and adds that (pushes it) to the navigation stack. For example when you use GoBack() it pops it out of the stack and destroys it, but when it gets back to the previous page it doesn't call the constructor since that one was already in the stack and does not have to be recreated.
If you don't want to create a page every time you navigate to it, you should look into Navigation Models for Windows Phone for some ideas on how you can tackle this.

Is there a way in ActionScript to force an IMMEDIATE update of the stage, _not_ after an event?

I know the method MouseEvent.updateAfterEvent() or KeyboardEvent.updateAfterEvent() which will force a re-render of the stage just after the event is handled rather than waiting for the next frame.
However, I need a method to force an immediate render at the very moment I call it. Is there such a method?
Actually my problem comes from the demential design of ActionScript's printing API (PrintJob). Inconsistent with the whole ActionScript architecture, when you call PrintJob.start(), everything is completely frozen while the printing dialog is shown until the user clicks the print or cancel button. Execution of any code after the PrintJob.start() call is resumed after that.
Among a lot of other much worse issues coming from this gigantic design flaw, there is mine:
public function someMouseOrKeyboardEventHandler() {
somethingThatUpdatesTheDisplayList();
var somePrintJob=new PrintJob();
somePrintJob.start();
//...
somePrintJob.send();
}
When this handler of mine is called, the changes made to the display list will not be visible until after the printing dialog has been closed, so I can't, for example, show something on the screen just before I open the print dialog.
updateAfterEvent() won't help a bit (already tried it). It won't change a thing, since it only forces rendering after the event handler code is executed.
Is there any updateRightNow()-like thing?
Nope, you unfortunately can't force an update in the middle of your code.
You can, however, wait until the next frame to call start() on the PrintJob; this will give Flash time to update the stage before everything freezes.

Force immediate layout and paint in Swing

I cannot seem to force a layout in Swing. I have a JComponent added to a JLayeredPane and I set a border on the JComponent. Then, I want to immediately re-draw everything - not in the sense of "please do this asap" like invalidate(), but synchronously and immediately. Any help? I cannot seem to find the right method of doing this, and all my reading about invalidate(), validate(), repaint(), doLayout(), etc is just confusing me more!
According to this (see the section titled "Synchronous Painting") the paintImmediately() method should work.
The most reliable way to get Swing to update a display is to use SwingUtilities.invokeLater. In your case, it would look something like
SwingUtilities.invokeLater(new Runnable {
public void run() {
somecomponent.repaint();
}
});
I realize the 'invokelater' does not exactly sound like it does anything immediate, but in practice, events posted in this way tend execute pretty quickly compared to just calling e.g. somecomponent.repaint() directly. If you absolutely must make your control code wait for the GUI to update, then there is also invokeAndWait, but my experience is that this is rarely necessary.
See also: document on event dispatch in Swing.
This is super old, but I found a simple solution, which I'll show with a JPasswordField:
var pw = new JPasswordField();
...
pw.paint(pw.getGraphics()); // paints immediately