Can a value from a JTextField be forced into the ValueModel (JGoodies)

半世苍凉 提交于 2019-12-22 17:38:20

问题


I have this code:

this.trigger = new Trigger();
this.presentationModel = new PresentationModel(this.personBean, this.trigger);
final ValueModel firstNameAdapter = presentationModel.getBufferedModel("firstName");
final JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);

and

firstNameTextField.addActionListener(new ActionListener() 
    {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            trigger.triggerCommit();
        }
    });

So when I push the enter button on the JTextField, I expect the value in my ValueModel class to be the same as the value in my JTextField. This doesn't happen unless I click outside the JTextField, then back inside the JTextField, and then push enter. If I just type in the text and hit enter, the ValueModel does not get the updated value. I am stuck on this problem, can anybody help?

BTW, I used this link for figuring out JGoodies in the first place: JGoodies Tutorial


回答1:


I hope I am understanding your question correctly.

You need to get the text in the text field and set it in the ValueModel.

firstNameTextField.addActionListener(new ActionListener()      
{         
    @Override         
    public void actionPerformed(ActionEvent e)          
    {
       //this get the text from the text field
       String firstName = firstNameTextField.getText();

       //now write your code to set the firstname into the ValueModel


       trigger.triggerCommit();
    }     
 }); 



回答2:


I looked through the JGoodies API (should have done this sooner) and found an unexpected static call, Bindings.commitImmediately()

If I call this method before my call to trigger.triggerCommit(), everything works as expected :)




回答3:


Create a text field that commits on each key typed instead of when focus is lost:

BasicComponentFactory.createTextField(firstNameAdapter, false);

Also, you should consider architecting your program to not use buffered models. I find that they make things more complicated and tricky, and think I saw Karsten Lentzsch recommending not to use them as well in a mailing list.

The most useful way for me to learn JGoodies was to look at the tutorial code for the JGoodies binding and validation libraries.



来源:https://stackoverflow.com/questions/4727028/can-a-value-from-a-jtextfield-be-forced-into-the-valuemodel-jgoodies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!