小编典典

这是将FocusListener添加到Java中的JTextFields的正确方法吗?

java

JTextFields在Java应用程序中有成百上千的应用程序,我想添加FocusListener所有这些来 设置 文本的“
水平对齐” ,并在每个这些文本字段上 添加FocusListener
。因此,我做了这种方法,效果很好。但是我只是想知道这种正确的方法还是其中存在错误,或者我违反某种OOP规则?

这是代码

public void CreateFocusListenerForFields(JTextField txt)
{
    txt.setHorizontalAlignment(JTextField.RIGHT);
    txt.addFocusListener(new FocusListener() 
    {
        @Override
        public void focusGained(FocusEvent e) {
        }

        @Override
        public void focusLost(FocusEvent e) {
            if(!NumberUtils.isNumber(txt.getText()))
            {
                txt.setBackground(new Color(254,157,157));
                txt.requestFocus();
            }
            else
            {
                txt.setBackground(Color.white);
            }
        }
    });
}

并将此方法应用于我的文本字段

CreateFocusListenerForFields(MyTextField);

现在,当我运行代码时,它非常有用,只是想知道这是否正确,如果不正确,那么当您必须在数百个字段上设置对齐方式和焦点侦听器时,还有另一种方法吗?多谢您的建议。


阅读 251

收藏
2020-11-26

共1个答案

小编典典

再次,我的偏见是使用InputVerifier而不是FocusListener,仅是因为InputVerifier是较高级别的构造,并且在适用的情况下,使用它们代替较低级别(更接近金属)的构造对我来说总是更安全。

两者的一个示例:

import java.awt.Color;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;

public class TestFieldVerification {
   public static final Color ERROR_COLOR = new Color(254,157,157);
   private static final int COLS = 8;
   private JPanel mainPanel = new JPanel();
   private JTextField verifiedField = new JTextField(COLS);
   private JTextField focusCheckedField = new JTextField(COLS);
   private Color defaultBackground = null;

   public TestFieldVerification() {
      verifiedField.setInputVerifier(new MyVerfier(this));
      focusCheckedField.addFocusListener(new MyFocusCheck(this));

      mainPanel.add(new JLabel("With InputVerfier:"));
      mainPanel.add(verifiedField);
      mainPanel.add(new JLabel("With FocusListener:"));
      mainPanel.add(focusCheckedField);
   }

   public boolean verifyText(String text) {
      try {
         Integer.parseInt(text);
         return true;
      } catch (NumberFormatException nfe) {
         return false;
      }
   }

   public void setFieldBackground(JComponent component, boolean verified) {
      if (defaultBackground == null) {
         defaultBackground = component.getBackground();
      }
      Color bg = verified ? defaultBackground : ERROR_COLOR;
      component.setBackground(bg);
   }

   public JComponent getMainPanel() {
      return mainPanel;
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("MyVerifier");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new TestFieldVerification().getMainPanel());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

class MyVerfier extends InputVerifier {
   private TestFieldVerification gui;

   public MyVerfier(TestFieldVerification gui) {
      this.gui = gui;
   }

   @Override
   public boolean shouldYieldFocus(JComponent input) {
      gui.setFieldBackground(input, super.shouldYieldFocus(input));
      return super.shouldYieldFocus(input);
   }

   @Override
   public boolean verify(JComponent input) {
      String text = ((JTextComponent) input).getText();
      return gui.verifyText(text);
   }

}

class MyFocusCheck extends FocusAdapter {
   private TestFieldVerification gui;

   public MyFocusCheck(TestFieldVerification gui) {
      this.gui = gui;
   }

   @Override
   public void focusLost(FocusEvent e) {
      JTextComponent textComp = (JTextComponent) e.getSource();
      String text = textComp.getText();
      boolean verified = gui.verifyText(text);
      gui.setFieldBackground(textComp, verified);
      if (!verified) {
         textComp.requestFocusInWindow();
      }
   }
}
2020-11-26