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

标签 java swing focus

我的 Java 应用程序中有数百个 JTextFields,我想在所有这些上添加 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);

现在,当我运行代码时,它工作得很好,只是想知道这是否正确,如果不正确,那么当您必须在数百个字段上设置对齐和焦点监听器时,其他出路是什么?感谢您的好意建议。

最佳答案

再说一遍,我的偏见是使用 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();
      }
   }
}

关于java - 这是在 java 中将 FocusListener 添加到 JTextFields 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26423468/

相关文章:

java - 如何在 JPanel 中启用溢出滚动条?

java - 发送海量数据——java解决方案

java - 无法将 Log4J 中的事件获取到 Flume 中

java - Hibernate 是否必须驱动数据库设计?

java - 无法在 linux 服务器上第二次获得 JDialog 中使用的 JTextField 的焦点

Java JDialog 交互,无需关注 macOS

qt - QML - 如何知道 child 是否有键盘焦点

java - 是否可以浏览网站 "without a browser"?

java - 用 ScrollingImagePanel 替换 JPanel?

java - 2D JComboBox,其中一个使用 ActionListener 控制另一个项目