在验证JTextFields的数值是否大于0后,在java中启用JButtons?

时间:2012-10-12 02:50:43

标签: java swing jtextfield documentlistener inputverifier

只有当所有字段中都存在有效数据时,才会启用两个按钮,即数字值和无负数。您是如何做到的?

4 个答案:

答案 0 :(得分:5)

我会考虑使用一个DocumentListener来监听JTextFields所持有的Documents。在这个网站上有这种事情的例子(我知道,因为我写了一两个)。

例如,

import java.awt.Component;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.JTextComponent;

public class DocumentListenerFun extends JPanel {
   private static final int FIELD_COUNT = 5;
   private JTextField[] fields = new JTextField[FIELD_COUNT];
   private JButton fooBtn = new JButton("Foo");
   private JButton barBtn = new JButton("Bar");
   private MyFieldListener myFieldListener = new MyFieldListener();

   public DocumentListenerFun() {
      fooBtn.setEnabled(false);
      barBtn.setEnabled(false);
      for (int i = 0; i < fields.length; i++) {
         fields[i] = new JTextField(10);
         add(fields[i]);
         myFieldListener.addTextComponent(fields[i]);
      }
      myFieldListener.addComponentsToEnable(fooBtn);
      myFieldListener.addComponentsToEnable(barBtn);
      add(fooBtn);
      add(barBtn);
   }

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

      JFrame frame = new JFrame("DocumentListenerFun");
      frame.setDefaultCloseOperation(JFrame.EXIT_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();
         }
      });
   }
}

class MyFieldListener {
   private List<JTextComponent> textComponents = new ArrayList<JTextComponent>();
   private List<Component> componentsToEnable = new ArrayList<Component>();
   private MyDocListener myDocListener = new MyDocListener(this);

   public void addTextComponent(JTextComponent textComponent) {
      textComponents.add(textComponent);
      textComponent.getDocument().addDocumentListener(myDocListener);
   }

   public void addComponentsToEnable(Component comp) {
      componentsToEnable.add(comp);
   }

   public void docsChanged() {
      boolean textVerified = true;
      for (JTextComponent textComp : textComponents) {
         String text = textComp.getText();
         textVerified &= verifyText(text);
      }

      for (Component comp : componentsToEnable) {
         comp.setEnabled(textVerified);
      }

   }

   private boolean verifyText(String text) {
      try {
         int value = Integer.parseInt(text.trim());
         if (value > 0) {
            return true;
         }
      } catch (NumberFormatException e) {
         return false;
      }
      return false;
   }
}

class MyDocListener implements DocumentListener {

   private MyFieldListener myFieldListener;

   public MyDocListener(MyFieldListener myFieldListener) {
      this.myFieldListener = myFieldListener;
   }

   @Override
   public void changedUpdate(DocumentEvent e) {
      myFieldListener.docsChanged();
   }

   @Override
   public void insertUpdate(DocumentEvent e) {
      myFieldListener.docsChanged();
   }

   @Override
   public void removeUpdate(DocumentEvent e) {
      myFieldListener.docsChanged();
   }

}

答案 1 :(得分:5)

或者,请考虑shouldYieldFocus()的{​​{1}}方法,说明here并讨论here

答案 2 :(得分:0)

答案 3 :(得分:0)

如果您只是不想允许负值,那么您可以使用DocumentFilter。

/**
 * REF: http://www.coderanch.com/t/345628/GUI/java/DocumentFilter
 */
public class NumericFilter extends DocumentFilter {

    @Override
    public void insertString(DocumentFilter.FilterBypass fb, int offset,
            String text, AttributeSet attr) throws BadLocationException {
        fb.insertString(offset, text.replaceAll("\\D", ""), attr);
    }

    // no need to override remove(): inherited version allows all removals  
    @Override
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
            String text, AttributeSet attr) throws BadLocationException {
        fb.replace(offset, length, text.replaceAll("\\D", ""), attr);
    }
}

然后使用

((AbstractDocument)(new JTextField).getDocument()).setDocumentFilter(new NumericFilter());