Populating JTextField based on latest KeyStroke

本小妞迷上赌 提交于 2019-12-02 05:49:04

The use case in my UI is to populate two jTextField's based on double clicking items in a jlist.

Well, normally a UI should be designed so that you can use the mouse or the keyboard to invoke an Action. That is you should be able to double click or use the Enter key on the selected item.

Check out List Action for a simple class that allows you to implement this functionality by using an Action.

Now when you create your Action you can extend TextAction. Then you can use the getFocustComponent() method from the TextAction to determine the text component that last had focus and add the text from the selected item to that text field.

The basic code for the custom Action would be:

JList list = (JList)e.getSource();
JTextComponent textField = getFocusedComponent();
textField.setText( list.getSelectedValue().toString() );

Note: you will need to verify if focus is on one of the two fields if your window contains more than two text components.

To use the FocusListener approach you would need to define an instance variable in your class:

private JTextField lastFocusedTextField = null;

Then in the constructor of your class where you create the text fields you would create the listener:

FocusListener fl = new FocusAdapter()
{
    @Override
    public void focusGained(FocusEvent e)
    {
        lastFocusedTextField = (JTextField)e.getSource();
    }
};

JTextField textField1 = new JTextField(...);
textField1.addFocusListener( fl );
// same for the other text field

Now you need to add a MouseListener to the JList. In the mouseClicked(...) method you do something like:

JList list = (JList)e.getSource();
lastFocusedTextField.setText( list.getSelectedValue().toString() );

So you need:

  1. an instance variable
  2. a FocusListener
  3. a MouseListener

As everyone has suggested initialize a FocusListener to both the text fields and and point it to a string variable when either of the loses focus.

Code:

String LastFocusLost = null;

jTextField1.addFocusListener(new java.awt.event.FocusAdapter()
 {
  public void focusLost(java.awt.event.FocusEvent evt)
     {
      LastFocusLost = "jTextField1";
     }  
 });

jTextField2.addFocusListener(new java.awt.event.FocusAdapter()
 {
  public void focusLost(java.awt.event.FocusEvent evt)
     {
      LastFocusLost = "jTextField2";
     }  
 });

In the mouseListener add a if-else then:

if ("jTextField1".equals(LastFocusLost))
 {
   //;
 }

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