-1

I'm making a GUI. In which user enter year in integers form and that year display on GUI. But the problem is i want to only enter 4 integers from user. If user enter 5 integers value then it show JOptionPane message please type again. But i don't know how to do it.

Code:

public class A extends JFrame{


    private JTextField tx;
    private JLabel year;
    private JButton bt;
    private JLabel at;


    public A(){
        super("Frame");


        getContentPane().setLayout(null);


        tx= new JTextField();
        tx.setBounds(150, 165, 128, 27);
        getContentPane().add(tx);   

        year= new JLabel("Enter Year :");
        year.setBounds(178, 133, 69, 27);
        getContentPane().add(year);


        at= new JLabel();
        at.setFont(new Font("Tahoma", Font.PLAIN, 17));
        at.setBounds(165, 295, 189, 27);
        getContentPane().add(at);


        bt= new JButton("Submit");
        bt.setBounds(178, 203, 84, 27);
        getContentPane().add(bt);
        bt.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {

                String w = tx.getText();
                int p = Integer.parseInt(w);

                 at.setText(""+p);

            }

        });

        setSize(450,450);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);


    }

}

Main

public class Main {

    public static void main(String[] args) {

        A obj = new A();


    }

} 
hamel123
  • 304
  • 4
  • 18
  • Convert the integer to string using String.valueOf(integer object) and then check length of the string... – We are Borg Jul 03 '15 at 15:43
  • Use `DocumentFilter` for this purpose to solve both thingies. First to [allow only digits in JTextField](http://stackoverflow.com/a/9478124/1057230) and to [set Maximum number of characters](http://stackoverflow.com/a/8883693/1057230), that can be inserted – nIcE cOw Jul 03 '15 at 15:43
  • @nIcE cOw can you please give me a code how to implement on this program – hamel123 Jul 03 '15 at 15:45
  • 3
    @hamel123 alternatively I think a `JSpinner` may be more suitable... – tonychow0929 Jul 03 '15 at 15:47
  • 1
    @hamel123 this isn't a code writing service – Daniel M. Jul 03 '15 at 15:47
  • @Daniel M i'm only saying that how to implement Document Filter on this program – hamel123 Jul 03 '15 at 15:49
  • @hamel123: Sorry mate, but writing code, will mean, I be blocking your way in learning, though I have given you example codes, and as rightly pointed out `JSpinner` is a very good alternative. Moreover, stop using `AbsolutePositioning` instead use a `LayoutManager` for arranging components. You simply have to do something like this `((AbstractDocument)tField.getDocument()).setDocumentFilter( new MyDocumentFilter()); `, in your code – nIcE cOw Jul 03 '15 at 15:50
  • Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Jul 03 '15 at 23:00

4 Answers4

2

Here is the code, for your quick review, but please try to implement thingies by yourself, in future.

import java.awt.*;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class MyDocumentFilterExample {

    private static final int MAX_CHARACTERS = 4;
    private JTextField tField;

    private void displayGUI () {
        JFrame frame = new JFrame("Input Integer Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5));
        tField = new JTextField(10);
        ((AbstractDocument)tField.getDocument()).setDocumentFilter(
                new MyDocumentFilter ( MAX_CHARACTERS ));        
        contentPane.add(tField); 

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main ( String[] args ) {
        Runnable runnable = new Runnable () {
            @Override
            public void run () {
                new MyDocumentFilterExample ().displayGUI ();
            }
        };
        EventQueue.invokeLater ( runnable );
    }
}

class MyDocumentFilter extends DocumentFilter {

    private int max_Characters;
    private boolean DEBUG;

    public MyDocumentFilter(int max_Chars) {
        max_Characters = max_Chars;
        DEBUG = false;
    }

    public void insertString(FilterBypass fb
                                    , int offset
                                    , String str
                                    , AttributeSet a) 
                                    throws BadLocationException {
        if (DEBUG) {
            System.out.println("In DocumentSizeFilter's insertString method");
        }
        int length = fb.getDocument ().getLength () + str.length ();
        if (length <= max_Characters && isValid ( str ) ) 
            super.insertString(fb, offset, str, a);
        else 
            Toolkit.getDefaultToolkit().beep();
    }

    public void replace(FilterBypass fb
                            , int offset, int length
                            , String str, AttributeSet a)
                                throws BadLocationException {
        if (DEBUG) {
            System.out.println("In DocumentSizeFilter's replace method");
        }
        int len = fb.getDocument ().getLength () + str.length ();
        if (len - length <= max_Characters && isValid ( str ) ) 
            super.replace(fb, offset, length, str, a);
        else
            Toolkit.getDefaultToolkit().beep();
    }

    private boolean isValid ( String string ) {
        int len = string.length();
        boolean isValidInteger = true;

        for (int i = 0; i < len; i++)
        {
            if (!Character.isDigit(string.charAt(i)))
            {
                isValidInteger = false;
                break;
            }
        }
        return isValidInteger;
    }
}
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
1

Just don't allow them in the first place to enter more than 4 chars

tx.addKeyListener(new KeyAdapter() {
      @Override
      public void keyTyped(KeyEvent e) {
          if (tx.getText().length() >= 4) {
              e.consume();
          }
      }
  });

You could then also expand this to make sure that they only enter numbers as well

tx.addKeyListener(new KeyAdapter() {
      @Override
      public void keyTyped(KeyEvent e) {
          if (tx.getText().length() >= 4 || !Character.isDigit(e.getKeyChar())) {
              e.consume();
          }
      }
  });
JDrost1818
  • 1,116
  • 1
  • 6
  • 23
1

In short you are checking if user entered a valid year. A logical approach will be much better in this case. In real case every app has a certain year range for user. You can do something like that.

String w = tx.getText();
int p = Integer.parseInt(w);
int lower_limit = 1960;
int upper_limit = 2050;
if(p>lower_limit && p<uppper_limit){
   at.setText(""+p);
}

But the best way is to use a JSpinner . It suits the purpose.

Note : If you really want all the 4 digit years , replace upper_limit and lower_limit with 10000 and 999 respectively.

Rahul
  • 289
  • 2
  • 7
0
    String w = tx.getText();
            int p = Integer.parseInt(w);

            String e=String.valueOf(w);
    int m = e.length();
    System.out.println(m);

    if(e.length()==4){


             at.setText(""+p);
    }
    else{
        JOptionPane.showMessageDialog(null, "Wrong");
    }
        }   

    });

Guys does this thing is good for pratice

hamel123
  • 304
  • 4
  • 18