Populating JTextField based on latest KeyStroke

前端 未结 2 1112
天命终不由人
天命终不由人 2021-01-24 04:28

The use case in my UI is to populate two JTextField components based on double clicking items in a JList. The easy was is to use a JCheckBox

2条回答
  •  遥遥无期
    2021-01-24 05:15

    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

提交回复
热议问题