这是正确的方法来在Java中添加FocusListener到JTextFields? [英] Is this Correct way to add FocusListener to JTextFields in java?

查看:175
本文介绍了这是正确的方法来在Java中添加FocusListener到JTextFields?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Java应用程序中,有数百个 JTextFields ,我想在所有这些元素上添加 FocusListener 在每个文本字段上设置水平对齐文本和添加FocusListener 。所以,我做了这个方法,效果很好。但我只是想知道,如果这个正确的方式或有什么问题,或者我反对某种规则的OOP?

这是代码 p>

  public void CreateFocusListenerForFields(JTextField txt)
{
txt.setHorizo​​ntalAlignment(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); 

现在,当我运行代码时,它的工作很好,只是想知道这是否正确,如果不那么当你需要在数百个字段上设置对齐和focuslistener时,还有什么办法呢?感谢您的好意。

解决方案

同样,我的偏见是使用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);
私有颜色defaultBackground = null;
$ b $ 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);

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


$ b $ public void setFieldBackground(JComponent component,boolean verified){
if(defaultBackground == null){
defaultBackground = component.getBackground ();
}
颜色bg =已验证? 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扩展了InputVerifier {
private TestFieldVerification gui;

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

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

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

}

class MyFocusCheck扩展了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();
}
}
}


I got hundreds of JTextFields in my application in Java and I want to add FocusListener on all of these to set Horizontal Alignment of text and add FocusListener on each of these textfields. So, I made this method and it's working great. But I just wanted to know if this correct way or there is something wrong in it or I am going against some kind of rule of OOPs?

Here is the code

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);
            }
        }
    });
}

And apply this method on my textfields

CreateFocusListenerForFields(MyTextField);

Now when I run code, it works great just wanted to know if this correct or not and if not then what is the other way out when you have to set alignment and focuslistener on hundreds of fields? Thanks for your kind advice.

解决方案

Again, my bias is to use an InputVerifier instead of a FocusListener, if only because the InputVerifier is a higher level construct, and it always seems safer to me to use these in place of lower level (closer to the metal) constructs where applicable.

An example of both:

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中添加FocusListener到JTextFields?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆