How to get on keyPressed in a JPanel CTRL+m? - swing

I'm trying to implement a JPopupMenu over a text editor component. It should be activated on CTRL+m. Can I do that inside
#Override
public void keyPressed(KeyEvent arg0) {
}
and if yes, how? Because if I try
if(arg0.isControlDown()&&arg0.getKeyChar()=='m')
it doesn't work.

At first I thought it was something to do with CTRL+M being the same thing as a carriage-return/line feed, but that wasn't true. Try:
if(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_M) {
System.out.println("pressed");
menu.setVisible(true);
}
I couldn't get it to work using chars with e.getKeyChar() either, but the getKeyCode() works for me. Great, it works. But I'm the type that has to know why. So I found this:
KEY_PRESSED and KEY_RELEASED events
are not intended for reporting of
character input. Therefore, the values
returned by this method are guaranteed
to be meaningful only for KEY_TYPED
events

Related

Junit testing in java for void methods

How to write test case for this function in a binary search tree ?
void insert(String key){
root=insertRec(root,key);
}
Your method does something. It obviously changes the state of the object by inserting a rec(ord?) and somehow re-evaluating what the root is. So, to test it, you should somehow be able to determine the new state, for example...
public void insert_should_create_new_record_and_set_root() {
assertThat( myObject.getRec( originalRoot) ).isNull();
Object originalRoot = myObject.getRoot();
myObject.insert("xyz");
assertThat( myObject.getRec( originalRoot) ).isEqualTo( "xyz"); // using AssertJ style here
assertThat( myObject.getRoot().value() ).isNotEqualTo( originalRoot );
}
If, on the other hand, you have no way to check the state from the outside, then you'll have a problem. But somehow your class has to communicate to the outside, hasn't it? If you really think that you cannot check the new state, then you'll have to provide more code of this class, as this answer is, of course, very general (which means "guessing", here).

Password field color

I want to change the color of my JPasswordField with key Listener. I'm making a registration form and the user should fill the passwordfield at least with 8 characters that include digits and letters. Can anybody help me?
my code :
enter code here
public void keyPressed(KeyEvent e) {
if(e.getSource()==passwordField){
if(passwordField.toString().length()>=8)
passwordField.setBackground(Color.GREEN);
else
passwordField.setBackground(Color.RED);
}
}
When the keyPressed() event is fired the Document of the password field has not yet been updated, so the length will be 1 less than you think it should be.
Instead try using the keyTyped() method:
public void keyTyped(KeyEvent e)
{
JPasswordField password = (JPasswordField)e.getSource();
if(passwordField.getPassword().length >= 8)
passwordField.setBackground(Color.GREEN);
else
passwordField.setBackground(Color.RED);
}
Also, when writing a listener you should get the source of the event from the event object instead of trying to access an instance variable.
You may also want to consider using an InputVerifier on this field. The input verifier will prevent the user from tab away from this field unless at least 8 digits have been entered.
Note: even using the keyTyped() event you can still have problems because if the user uses the "BackSpace" key no event is generated. So maybe you should be using the keyRelased() event. Even this can cause a problem because if the users holds down a key multiple characters will be entered into the field before a keyReleased event is fired.
The best solution is to use a Document Listener. Read the section from the Swing tutorial on How to Write a Document Listener for more information.
you're doing it wrong
change to this
public void keyPressed(KeyEvent e) {
if(e.getSource()==passwordField){
if(passwordField.getPassword().length()>=8)
passwordField.setBackground(Color.GREEN);
else
passwordField.setBackground(Color.RED);
}
}
you should use getPassword()

How to use the result of this method?

I'm developing in AS3 for the Doubleclick platform, though this may be more of a generic programming question.
I am trying to determine whether a video is playing or paused. Doubleclick has the following method:
videoController.getPlayerState()
Which when traced, returns either:
[object PlayingState]
or
[object PausedState]
My question is, how do I do work with that result? I just want to turn it into a boolean that I can use in an if statement to call, or not call, another function.
Like:
if([object PlayingState]){ doSomething(); } else {doNothing(); }
Except that you can't do that, because whenever I try to do anything like that I get an error!! And I can't figure out how you're supposed to do this.
I'm sure this is super-basic. Can anyone enlighten me??
Thanks so much!!
Look at this doc PlayingState
The PlayingState and PausedState class extends AbstractPlayerState,
And AbstractPlayerState get a function getStateType said like this
getStateType() : String
Returns the player state as a string such as "InitialState","BufferingState",
"LoadingState", "PausedState", "PlayingState", or "StoppedState".
It is encouraged to use videoController.getPlayerState() and match against the
relevant class using instanceof or is.
So I think you can do like this
var state:AbstractPlayerState = videoController.getPlayerState();
if (state is PlayingState) {
} else if ( state is PausedState) {
}

How to do CreateBindingSet() on Windows Phone?

In the N+1 video #34 (Progress), there was an example of using CreateBindingSet() for the Android version, which is not typical. But the narrator also mentioned briefly that the same can be done on the Windows platform.
As much as I tried, however, I am unable to get a View's property to be bound to its ModelView on the Windows Phone. I always get a NullReferenceException.
The closest I came was the code below, including suggestions from ReSharper. Here's my FirstView.xaml.cs:
using Cirrious.MvvmCross.Binding.BindingContext;
using Whatever.ViewModels;
namespace Whatever {
// inheriting from IMvxBindingContextOwner was suggested by ReSharper also
public partial class FirstView : BaseView, IMvxBindingContextOwner {
public class MyBindableMediaElement
{
private string _theMediaSource = "whatever";
public string TheMediaSource
{
get
{
return _theMediaSource;
}
set
{
_theMediaSource = value;
}
}
}
public FirstView()
{
InitializeComponent();
_mediaElement = new MyBindableMediaElement(this.theMediaElement);
var set = this.CreateBindingSet<FirstView, FirstViewModel>();
// the corresponding view model has a .SongToPlay property with get/set defined
set.Bind(_mediaElement).For(v => v.TheMediaSource).To(vm => vm.SongToPlay);
set.Apply();
}
public IMvxBindingContext BindingContext { get; set; } // this was suggested by ReSharper
}
I get a NullReferenceException in MvxBaseFluentBindingDescription.cs as soon as the view is created. The exact location is below:
protected static string TargetPropertyName(Expression<Func<TTarget, object>> targetPropertyPath)
{
var parser = MvxBindingSingletonCache.Instance.PropertyExpressionParser; // <----- exception here**
var targetPropertyName = parser.Parse(targetPropertyPath).Print();
return targetPropertyName;
}
I have not seen a working example of creating a binding set on a Windows Phone emulator. Has anyone gotten this to work? Thanks.
I can confirm that the narrator said that remark a little too flippantly without actually thinking about how he might do it...
However, with a little effort, you definitely can get the CreateBindingSet to work in Windows if you want to.
Before you start, do consider some alternatives - in particular, I suspect most people will use either Windows DependencyProperty binding or some hand-crafted code-behind with a PropertyChanged event subscription.
If you do want to add CreateBindingSet code to a Windows project then:
Add the Binding and BindingEx assemblies to your Ui project - the easiest way to do this is using nuget to add the BindingEx package.
In your Setup class, override InitializeLastChance and use this opportunity to create a MvxWindowsBindingBuilder instance and to call DoRegistration on that builder. Both these first two steps are covered in the n=35 Tibet binding video - and it's this second step that will initialise the binding framework and help you get past your current 'NullReferenceException' (for the code, see BindMe.Store/Setup.cs)
In your view, you'll need to implement the IMvxBindingContextOwner interface and you'll need to ensure the binding context gets created. You should be able to do this as simply as BindingContext = new MvxBindingContext();
In your view, you'll need to make sure the binding context is given the same DataContext (view model) as the windows DataContext. For a Phone Page, the easiest way to do this is probably just to add BindingContext.DataContext = this.ViewModel; to the end of your phone page's OnNavigatedTo method. Both steps 3 and 4 could go in your BaseView if you intend to use Mvx Binding in other classes too.
With this done, you should be able to use the CreateBindingSet code - although do make sure that all binding is done after the new MvxBindingContext() has been created.
I've not got a windows machine with me right now so I'm afraid this answer code comes untested - please do post again if it does or doesn't work.
I can confirm it works almost perfectly; the only problem is, there are no defaults register, so one has to do the full binding like:
set.Bind(PageText).For(c => c.Text).To(vm => vm.Contents.PageText).OneTime();
to fix this, instead of registering MvxWindowsBindingBuilder, I am registering the following class. Note: I have just created this class, and needs testing.
public class UpdatedMvxWindowsBindingBuilder : MvxWindowsBindingBuilder
{
protected override void FillDefaultBindingNames(IMvxBindingNameRegistry registry)
{
base.FillDefaultBindingNames(registry);
registry.AddOrOverwrite(typeof(Button), "Command");
registry.AddOrOverwrite(typeof(HyperlinkButton), "Command");
//registry.AddOrOverwrite(typeof(UIBarButtonItem), "Clicked");
//registry.AddOrOverwrite(typeof(UISearchBar), "Text");
//registry.AddOrOverwrite(typeof(UITextField), "Text");
registry.AddOrOverwrite(typeof(TextBlock), "Text");
//registry.AddOrOverwrite(typeof(UILabel), "Text");
//registry.AddOrOverwrite(typeof(MvxCollectionViewSource), "ItemsSource");
//registry.AddOrOverwrite(typeof(MvxTableViewSource), "ItemsSource");
//registry.AddOrOverwrite(typeof(MvxImageView), "ImageUrl");
//registry.AddOrOverwrite(typeof(UIImageView), "Image");
//registry.AddOrOverwrite(typeof(UIDatePicker), "Date");
//registry.AddOrOverwrite(typeof(UISlider), "Value");
//registry.AddOrOverwrite(typeof(UISwitch), "On");
//registry.AddOrOverwrite(typeof(UIProgressView), "Progress");
//registry.AddOrOverwrite(typeof(IMvxImageHelper<UIImage>), "ImageUrl");
//registry.AddOrOverwrite(typeof(MvxImageViewLoader), "ImageUrl");
//if (_fillBindingNamesAction != null)
// _fillBindingNamesAction(registry);
}
}
This is a skeleton from Touch binding, and so far I have only updated three controls to test out (Button, HyperButton and TextBlock)

Make Flex TextInput show no prompt on empty String

I am using a s:TextInput in Flex 4.5. It shows it's prompt text if the underlying text value is null or empty String. Does anybody know if I can make either don't show the prompt on empty String or even show a different prompt?
I already found a way by extending the TextInput class and overriding some of the methods but I am still hoping anyone here knows an easier way ;-)
Ok, so based on the comments, here it is:
You store the current prompt value in a private variable, like so:
private var _inputPrompt:String = "";
Then you create a getter, so the value is accessible from outside of this class:
public function get inputPrompt():String
{
return _inputPrompt;
}
Now you can bind inputPrompt anywhere you need it, however, the problem is the getter won't be recalled once the private value changes. You can fix this very easily: Create an update method, for example like so:
public function updateInputPrompt(value:String):void
{
_inputPrompt = value;
}
Ok, nothing fancy so far. I'm guessing this is the point where you are right now. In order to "force" the getter to be recalled, you have to bind it to an event, like so:
[Bindable(event="inputPromptUpdated")]
public function get inputPrompt():String
{
return _inputPrompt;
}
Finally, you can simply dispatch this event when the value is update (i.e. in the updateInputPrompt method):
public function updateInputPrompt(value:String):void
{
_inputPrompt = value;
dispatchEvent("inputPromptUpdated"); // For binding
}
This way, the getter will be recalled every time you dispatch that event.
Hope this helps. Have a great day, and a great weekend!