Interacting with multiple textfields with KeyListener for Java

帅比萌擦擦* 提交于 2019-12-25 03:47:06

问题


I'm making a small java program where I have two JTextFields labeled field1, field2. I have a calculate button as well which initially set to disabled. I want the button only to be enabled when the 2 text boxes have values in them. Currently what i have for the key listener is:

field1.addKeyListener(new java.awt.event.KeyAdapter()  {  
public void keyReleased(java.awt.event.KeyEvent evt) {  
        if (field1.getDocument().getLength() > 0) {  
            bt1.setEnabled(true);
            }
        else {  
            bt1.setEnabled(false);  
        }  
    }
}); 

Is there a way to include field 2 into the above block? I've tried just copying and pasting the same code block twice but changing the field1 to field2 but that still doesn't work.

Thanks for the help


回答1:


You really never want to use a KeyListener with a JTextField as this can mess up the JTextField's function. Much better is to use a DocumentListener and give it to both JTextField's Documents.

For example please check out this similar question

Or if you need to be notified of text changes before they are validated, use a DocumentFilter. For more on that, please see this question.

e.g.,

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class DocListenerEg extends JPanel {
   private JTextField field1 = new JTextField(10);
   private JTextField field2 = new JTextField(10);
   private JButton button = new JButton("Button");

   public DocListenerEg() {
      add(field1);
      add(field2);
      add(button);

      button.setEnabled(false);

      DocumentListener docListener = new DocumentListener() {

         @Override
         public void removeUpdate(DocumentEvent e) {
            checkForText();
         }

         @Override
         public void insertUpdate(DocumentEvent e) {
            checkForText();
         }

         @Override
         public void changedUpdate(DocumentEvent e) {
            checkForText();
         }

         private void checkForText() {
            boolean textOK = !field1.getText().trim().isEmpty() && !field2.getText().trim().isEmpty();
            button.setEnabled(textOK);
         }
      };
      field1.getDocument().addDocumentListener(docListener);
      field2.getDocument().addDocumentListener(docListener);
   }

   private static void createAndShowGui() {
      DocListenerEg mainPanel = new DocListenerEg();

      JFrame frame = new JFrame("DocListenerEg");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}



回答2:


You current requirement may be for only two text fields, but you should always design to be more flexible and allow any number of text fields. This also allows the code to be reusable.

Something like:

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.*;

public class DataEntered implements DocumentListener
{
    private JButton button;
    private List<JTextField> textFields = new ArrayList<JTextField>();

    public DataEntered(JButton button)
    {
        this.button = button;
    }

    public void addTextField(JTextField textField)
    {
        textFields.add( textField );
        textField.getDocument().addDocumentListener( this );
    }

    public boolean isDataEntered()
    {
        for (JTextField textField : textFields)
        {
            if (textField.getText().trim().length() == 0)
                return false;
        }

        return true;
    }

    @Override
    public void insertUpdate(DocumentEvent e)
    {
        checkData();
    }

    @Override
    public void removeUpdate(DocumentEvent e)
    {
        checkData();
    }

    @Override
    public void changedUpdate(DocumentEvent e) {}

    private void checkData()
    {
        button.setEnabled( isDataEntered() );
    }

    private static void createAndShowUI()
    {
        JButton submit = new JButton( "Submit" );
        submit.setEnabled( false );

        JTextField textField1 = new JTextField(10);
        JTextField textField2 = new JTextField(10);

        DataEntered de = new DataEntered( submit );
        de.addTextField( textField1 );
        de.addTextField( textField2 );

        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textField1, BorderLayout.WEST);
        frame.add(textField2, BorderLayout.EAST);
        frame.add(submit, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}


来源:https://stackoverflow.com/questions/25477133/interacting-with-multiple-textfields-with-keylistener-for-java

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