2016-10-14 13 views
-1

für eine kleine Testanwendung Ich brauche ein TextField, das nur Zahlen akzeptiert. Außerdem sollte der Benutzer nur Zahlen von 0-255 eingeben können. Bisher fand ich dies:JTextfield akzeptiert nur Zahlen zwischen 0-255

import javax.swing.JTextField; 
import javax.swing.text.AttributeSet; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.Document; 
import javax.swing.text.PlainDocument; 

/** 
* A JTextField that accepts only integers. 
* 
* @author David Buzatto 
*/ 
public class IntegerField extends JTextField { 

    public IntegerField() { 
     super(); 
    } 

    public IntegerField(int cols) { 
     super(cols); 
    } 

    @Override 
    protected Document createDefaultModel() { 
     return new UpperCaseDocument(); 
    } 

    static class UpperCaseDocument extends PlainDocument { 

     @Override 
     public void insertString(int offs, String str, AttributeSet a) 
       throws BadLocationException { 

      if (str == null) { 
       return; 
      } 

      char[] chars = str.toCharArray(); 
      boolean ok = true; 

      for (int i = 0; i < chars.length; i++) { 

       try { 
        Integer.parseInt(String.valueOf(chars[i])); 
       } catch (NumberFormatException exc) { 
        ok = false; 
        break; 
       } 
      } 

      if (ok) { 
       super.insertString(offs, new String(chars), a); 
      } 
     } 
    } 

I die for-Schleife hinzugefügt folgende so nur Zahlen, die aus 3 Ziffern enthalten

if(super.getLength() == 3) { 
     ok = false; 
     System.out.println("tooLong"); 
     break; 

    } 

Aber wie eingegeben werden kann ich einen maximalen Eingangswert? Der Benutzer sollte nur Zahlen eingeben, die von 0-255 gehen.

Vielen Dank im Voraus

+2

Eingang> = 0 && Eingang <= 255? – eldo

+0

Ich weiß, aber wie soll ich das umsetzen, woher bekomme ich/wie bekomme ich den Input? super.length() war einfach, aber wie mache ich super.getInput super.getText? – KilledByCheese

+0

Siehe http://StackOverflow.com/A/13424140/1076463 – Robin

Antwort

0

Sie diese beiden Kontrollen wie folgt implementieren:

 if(str.length()>3) { 
      return; 
     } 

     int inputNum = Integer.parseInt(str); 
     if(inputNum<0 || inputNum>255) { 
      return; 
     } 

diese Kontrollen hinzufügen vor dem letzten, wenn Block und Sie sollten gut zu gehen.

0

Hier ist der einfachste Weg zu tun, was Sie wollen.

import javax.swing.JFrame; 
import javax.swing.JTextField; 
import javax.swing.SwingUtilities; 
import javax.swing.WindowConstants; 

public class ByteField extends JTextField { 

    private boolean revert; 

    @Override 
    public void replaceSelection(String content) { 
     if (revert) { 
      super.replaceSelection(content); 
     } else { 
      String current = getText(); 
      super.replaceSelection(content); 
      String now = getText(); 
      try { 
       if (!now.isEmpty()) { 
        int val = Integer.valueOf(now); 
        revert = val < 0 || val > 255; 
       } 
      } catch (Exception e) { 
       revert = true; 
      } 
      if (revert) { 
       setText(current); 
      } 
      revert = false; 
     } 
    } 

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

      @Override 
      public void run() { 
       JTextField fld = new ByteField(); 
       fld.setColumns(5); 
       JFrame frm = new JFrame("Test"); 
       frm.add(fld); 
       frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
       frm.pack(); 
       frm.setLocationRelativeTo(null); 
       frm.setVisible(true); 
      } 
     }); 
    } 
} 

Und hier ist die Möglichkeit, das Dokument mit:

import javax.swing.JFrame; 
import javax.swing.JTextField; 
import javax.swing.SwingUtilities; 
import javax.swing.WindowConstants; 
import javax.swing.text.AttributeSet; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.PlainDocument; 

public class ByteField extends JTextField { 

    private static class ByteDocument extends PlainDocument { 

     @Override 
     public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { 
      String currText = getText(0, getLength()); 
      StringBuilder b = new StringBuilder(currText); 
      b.insert(offs, str); 
      currText = b.toString(); 
      boolean proceed = true; 
      try { 
       if (!currText.isEmpty()) { 
        int val = Integer.valueOf(currText); 
        proceed = val >= 0 && val <= 255; 
       } 
      } catch (Exception e) { 
       proceed = false; 
      } 
      if (proceed) { 
       super.insertString(offs, str, a); 
      } 
     } 
    } 

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

      @Override 
      public void run() { 
       JTextField fld = new JTextField(new ByteDocument(), "", 5); 
       JFrame frm = new JFrame("Test"); 
       frm.add(fld); 
       frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
       frm.pack(); 
       frm.setLocationRelativeTo(null); 
       frm.setVisible(true); 
      } 
     }); 
    } 
} 
+0

Bitte warum nicht mit DocumentFilter (AllLows Zahlen), oder JSpinner oder JFormattedTextField mit Min & Max im Formatierer – mKorbel

+0

@mKorbel Sie haben Recht. Es gibt viele Möglichkeiten, die erforderliche Funktionalität bereitzustellen. JSpinner/JFormattedTextField kann es noch einfacher machen, aber sie haben auch einige Einschränkungen. –

0

erhalten eine leere Warnung einen Haken, wenn Sie nichts hinzufügen Das wird den Job zu erledigen, obwohl ich betritt die Textinput Sie würde vorschlagen.

import java.awt.Dimension; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton;` 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JTextArea; 

public class Matches extends JFrame{ 

    JTextArea textInput = new JTextArea(1, 10); 
    JLabel labelInput = new JLabel("Enter a number between 0-255"); 
    JLabel labelOutput = new JLabel(); 
    JPanel p1 = new JPanel(); 
    JButton b1 = new JButton("Test Number"); 


    public Matches() { 
     p1.add(labelInput); 
     p1.add(textInput); 
     p1.add(b1); 
     p1.add(labelOutput); 
     b1.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       int answer = Integer.parseInt(textInput.getText()); 

       if (answer >= 0 && answer <= 255) { 
        labelOutput.setText("You entered: " + textInput.getText()); 
       } else { 
        JOptionPane.showMessageDialog(null, "Error!, only numbers between 0-255 are allowed!"); 
       } 

      } 
     }); 

     add(p1); 
     setVisible(true); 
     setSize(300, 300); 
     setLocationRelativeTo(null); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    public static void main(String[] args) { 

     new Matches(); 
    } 
} 
Verwandte Themen