Page 1 of 2 12 LastLast
Results 1 to 20 of 24
  1. #1
    globo is offline Member
    Join Date
    Sep 2010
    Posts
    61
    Rep Power
    0

    Default Key event + only number

    Hello
    I am trying to solve this problem.
    I have a JTextfield and I need that text field to accept only numbers.
    Once a user enters a character it will delete that character right away.

    Any idea of to do this?
    This is my program to have an idea it compiles and runs perfectly.

    Java Code:
    import java.awt.*;
     import java.awt.event.*;
     import javax.swing.*;
     import java.awt.event.KeyEvent.*;
    
    
       
    
       public class DoBills
       {
    
          public static void main(String [] args)
          {
    
             MyFrame frame = new MyFrame("Alan Jackson - Bills");
             frame.setSize(300, 300);
             frame.setLocation(300, 200);
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
    
          }
       }
    
       
    
       class MyFrame extends JFrame
    
       {  
    
          public static final int WIDTH = 7;
    
          
    
          JPanel pnlTitle = new JPanel();
          JPanel pnlIncome = new JPanel();
          JPanel pnlTax = new JPanel();
          JPanel pnlBills = new JPanel();
          JPanel pnlNet = new JPanel();
    
          
    
          JLabel lblTitle = new JLabel("Doing The Bills");
          JLabel lblIncome = new JLabel("Income: $");
          JLabel lblTax = new JLabel("Tax: $");
          JLabel lblBills = new JLabel("Bills: $");
    
          
    
          JTextField txtIncome = new JTextField("0", WIDTH);
          JTextField txtTax = new JTextField("0", WIDTH);
          JTextField txtBills = new JTextField("0", WIDTH);
    
         
          JTextField txtNet = new JTextField("0", WIDTH);    
          Finance finance = new Finance(5000, 0.25);
    
          
    
          public MyFrame(String s)
    
          {
    
             super(s);
             setLayout(new GridLayout(5, 1));
    
             
    
             pnlTitle.setLayout(new FlowLayout(FlowLayout.CENTER));
             pnlIncome.setLayout(new FlowLayout(FlowLayout.RIGHT));
             pnlTax.setLayout(new FlowLayout(FlowLayout.RIGHT));
             pnlBills.setLayout(new FlowLayout(FlowLayout.RIGHT)); 
             pnlNet.setLayout(new FlowLayout(FlowLayout.CENTER));
    
             
    
             txtTax.setEditable(false);
             txtNet.setEditable(false);
    
             
    
             lblTitle.setFont(new Font("Arial", Font.BOLD, 24));
             pnlTitle.add(lblTitle);
             add(pnlTitle);
    
             
    
             pnlIncome.add(lblIncome);
             pnlIncome.add(txtIncome);
             add(pnlIncome);
    			
             pnlTax.add(lblTax);
             pnlTax.add(txtTax);
             add(pnlTax);
          
    
             pnlBills.add(lblBills);
             pnlBills.add(txtBills);
             add(pnlBills);
    
    
             pnlNet.add(new JLabel("Net: $"));
             pnlNet.add(txtNet);
             add(pnlNet);
    
             updateNet();  
             txtIncome.addActionListener(new IncomeHandler());
             txtBills.addActionListener(new BillsHandler());
    			
    
          }
    
          
    
          private void updateNet()
          {
    
             txtNet.setText("" + finance.getNet());
             if (finance.getNet() >= 0)
             {
    
                txtNet.setBackground(Color.GREEN);
                lblTitle.setForeground(Color.GREEN);
    
             }
    
             else
             {
    
                txtNet.setBackground(Color.RED);
                lblTitle.setForeground(Color.RED);
    
             }
          }
    
          class IncomeHandler implements ActionListener
          {
    
             public void actionPerformed(ActionEvent event)
             {
    
                int val = Integer.parseInt( txtIncome.getText().trim() );
                finance.setIncome(val);
                txtIncome.setText("" + finance.getIncome());
                txtTax.setText("" + finance.getTax());
                updateNet();
    
             }
          }
    
          
    
          class BillsHandler implements ActionListener
          {
    
             public void actionPerformed(ActionEvent event)
             {
    
                int val = Integer.parseInt( txtBills.getText().trim() );
                finance.setBills(val);
                txtBills.setText("" + finance.getBills());
                updateNet();
    
             }
          }
       }
    
    
    
       class Finance
       {
    
          private int income;
          private int bills;
    
          private int max;
          private double taxRate;
          
          public Finance(int max, double taxRate)
          {
    
             setMax(max);
             this.taxRate = (taxRate >= 0.0 && taxRate <= 1.00) ? taxRate : 0.0;
    
          }
    
          private void setMax(int max)
          {
             this.max = (max >= 0) ? max : 0;
          }
     
          public void setIncome(int income)
          {
    
             if (income <= 0)
                this.income = 0;
    
             else if (income >= max)
    
                this.income = max;
             else
                this.income = income;
    
          }    
          public void setBills(int bills)
          {
    
             if (bills <= 0)
    
                this.bills = 0;
    
             else if (bills >= max)
    
                this.bills = max;
    
             else
    
                this.bills = bills;
    
          }
    
          
    
          public int getBills()
    
          {
    
             return bills;
    
          }
    
          
    
          public int getIncome()
    
          {
    
             return income;
    
          }
          public int getTax()
          {
    
             return (int)(income * taxRate);
    
          }
    
          
    
          public int getNet()
    
          {
    
             return income - getTax() - bills;
    
          }
    
       }

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,864
    Rep Power
    8

    Default

    Last edited by KevinWorkman; 11-04-2010 at 05:49 PM.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,336
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by globo View Post
    Hello
    I am trying to solve this problem.
    I have a JTextfield and I need that text field to accept only numbers.
    Take a look at the JFormattedTextField (it extends the JTextField class).

    kind regards,

    Jos

  4. #4
    coltragon is offline Senior Member
    Join Date
    Dec 2009
    Posts
    104
    Rep Power
    0

    Default

    I think the right way to do this is to create a Jtextfield with a NumberFormat.

    OnlyNmbersAllowed = new JFormattedTextField(NumberFormat.getInstance());

    EDIT: My message is not needed, while i was typing 2 others already replied :P
    Beginner in Java Programming, Please don't trust my anwsers blind please :D

  5. #5
    globo is offline Member
    Join Date
    Sep 2010
    Posts
    61
    Rep Power
    0

    Default

    What I need is some kind of keyboard event handling, and String processing, so that the program dynamically responds to the values entered in the Income and Bills text fields.
    I don't know how to implement this nor I know the right codes for it.

  6. #6
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,864
    Rep Power
    8

    Default

    And what was wrong with the answer(s) you received?

  7. #7
    globo is offline Member
    Join Date
    Sep 2010
    Posts
    61
    Rep Power
    0

    Default

    I saw that yesterday. The difference is that that one does not show the message at all.
    I need the character to show and then get deleted.
    I know it's kind of similar but this is what the homework asks.

  8. #8
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,864
    Rep Power
    8

    Default

    Okay, then in that case:

    Text Component Features (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)

    You might also need a Timer, depending on your actual requirements.

  9. #9
    globo is offline Member
    Join Date
    Sep 2010
    Posts
    61
    Rep Power
    0

    Default

    The method that is handled in this one is for document not JTextfield.
    I am not sure if this is what I am looking for?

  10. #10
    globo is offline Member
    Join Date
    Sep 2010
    Posts
    61
    Rep Power
    0

    Default

    I guess I need an key event listener and an exception handler that will handle the error when a user input a character. I will work on this first.

  11. #11
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,864
    Rep Power
    8

    Default

    Quote Originally Posted by globo View Post
    The method that is handled in this one is for document not JTextfield.
    I am not sure if this is what I am looking for?
    JTextField has a getDocument() function.

  12. #12
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,864
    Rep Power
    8

    Default

    Quote Originally Posted by globo View Post
    I guess I need an key event listener and an exception handler that will handle the error when a user input a character. I will work on this first.
    That'll work.

    By the way, the getDocument() function plus another way to ensure valid input are both covered in the JTextField API:JTextField (Java Platform SE 6)

  13. #13
    globo is offline Member
    Join Date
    Sep 2010
    Posts
    61
    Rep Power
    0

    Default

    I have one error with this code is when I click backspace it shows errors


    Java Code:
       import java.awt.*; 
       import java.awt.event.*; 
       import javax.swing.*; 
    
        public class  BetterBills 
       { 
           public static void main(String [] args) 
          { 
             MyFrame frame = new MyFrame("Alan Jackson - Bills"); 
             frame.setSize(300, 300); 
             frame.setLocation(300, 200); 
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
             frame.setVisible(true); 
          } 
       } 
    
        class MyFrame extends JFrame 
       { 
          public static final int WIDTH = 7; 
       
          JPanel pnlTitle = new JPanel(); 
          JPanel pnlIncome = new JPanel(); 
          JPanel pnlTax = new JPanel(); 
          JPanel pnlBills = new JPanel(); 
          JPanel pnlNet = new JPanel(); 
       
          JLabel lblTitle = new JLabel("Doing The Bills"); 
          JLabel lblIncome = new JLabel("Income: $"); 
          JLabel lblTax = new JLabel("Tax: $"); 
          JLabel lblBills = new JLabel("Bills: $"); 
       
          JTextField txtIncome = new JTextField("0", WIDTH); 
          JTextField txtTax = new JTextField("0", WIDTH); 
          JTextField txtBills = new JTextField("0", WIDTH); 
       
          JTextField txtNet = new JTextField("0", WIDTH); 
       
          Finance finance = new Finance(5000, 0.25); 
            
           public MyFrame(String s) 
          { 
             super(s); 
             setLayout(new GridLayout(5, 1)); 
          
             pnlTitle.setLayout(new FlowLayout(FlowLayout.CENTER)); 
             pnlIncome.setLayout(new FlowLayout(FlowLayout.RIGHT)); 
             pnlTax.setLayout(new FlowLayout(FlowLayout.RIGHT)); 
             pnlBills.setLayout(new FlowLayout(FlowLayout.RIGHT)); 
             pnlNet.setLayout(new FlowLayout(FlowLayout.CENTER)); 
          
             txtTax.setEditable(false); 
             txtNet.setEditable(false); 
          
             lblTitle.setFont(new Font("Arial", Font.BOLD, 24)); 
             pnlTitle.add(lblTitle); 
             add(pnlTitle); 
          
             pnlIncome.add(lblIncome); 
             pnlIncome.add(txtIncome); 
             add(pnlIncome); 
          
             pnlTax.add(lblTax); 
             pnlTax.add(txtTax); 
             add(pnlTax); 
          
             pnlBills.add(lblBills); 
             pnlBills.add(txtBills); 
             add(pnlBills); 
          
             pnlNet.add(new JLabel("Net: $")); 
             pnlNet.add(txtNet); 
             add(pnlNet); 
          
             updateNet(); 
          
             txtIncome.addActionListener(new IncomeHandler()); 
             txtBills.addActionListener(new BillsHandler()); 
             txtIncome.addKeyListener(new NumericKeyHandler());
          } 
       
           private void updateNet() 
          { 
             txtNet.setText("" + finance.getNet()); 
             if (finance.getNet() >= 0) 
             { 
                txtNet.setBackground(Color.GREEN); 
                lblTitle.setForeground(Color.GREEN); 
             } 
             else 
             { 
                txtNet.setBackground(Color.RED); 
                lblTitle.setForeground(Color.RED); 
             } 
          } 
       
           class IncomeHandler implements ActionListener 
          { 
              public void actionPerformed(ActionEvent event) 
             { 
                int val = Integer.parseInt( txtIncome.getText().trim() ); 
                finance.setIncome(val); 
                txtIncome.setText("" + finance.getIncome()); 
                txtTax.setText("" + finance.getTax()); 
                updateNet(); 
             } 
             
            
          } 
           
           class BillsHandler implements ActionListener 
          { 
              public void actionPerformed(ActionEvent event) 
             { 
                int val = Integer.parseInt( txtBills.getText().trim() ); 
                finance.setBills(val); 
                txtBills.setText("" + finance.getBills()); 
                updateNet(); 
             } 
          } 
           private class NumericKeyHandler implements KeyListener
          {
              public void keyPressed(KeyEvent e)
             {
             }
             
              public void keyReleased(KeyEvent e)
             {
             }
          	
              public void keyTyped(KeyEvent e)
             {
                char c = e.getKeyChar();
                if (!((c >= '0') && (c <= '9') ||
                (c == KeyEvent.VK_BACK_SPACE) ||
                (c == KeyEvent.VK_DELETE))) {
                   getToolkit().beep();
                   e.consume();
                   
                
                }
                else if((c >= '0') && (c <= '9'))
             	{
             	 int val = Integer.parseInt(txtIncome.getText().trim() );
                   finance.setIncome(val);
                   txtIncome.setText("" + finance.getIncome() );
                   txtTax.setText("" + finance.getTax()); 
                   updateNet();
             	
             	}
             
        /*     char c = e.getKeyChar();
                String s = txtIncome.getText().trim();
                int val = Integer.parseInt(s);     
                if((c >= '0') && (c <= '9' ))
                {
                   
                 //  int val = Integer.parseInt(txtIncome.getText().trim() );
                   
                   finance.setIncome(val);
                   txtIncome.setText("" + finance.getIncome());
                   txtTax.setText("" + finance.getTax()); 
                   updateNet();
                }	
                //else
                
                   // c = e.getKeyChar();
                   //if (!((c >= '0') && (c <= '9') ||
                   //(c == KeyEvent.VK_BACK_SPACE) ||
                   //(c == KeyEvent.VK_MINUS)
                   //)) {
                      //getToolkit().beep();
                      //e.consume();
                   //}*/
                
               
                boolean isBackspace;
                String s = txtIncome.getText().trim();
             
                if( isBackspace = e.getKeyChar() == '\u0008')
                {
                    s = txtIncome.getText().trim();
                
                   if( s == null)
                   {
                      txtIncome.setText("0");
                   }
                   else
                   {		 
                      int val = Integer.parseInt(txtIncome.getText().trim() );
                   
                      finance.setIncome(val);
                      txtIncome.setText("" + finance.getIncome() );
                      txtTax.setText("" + finance.getTax()); 
                      updateNet();
                   
                   /*       char c = e.getKeyChar();
                   if (!((c >= '0') && (c <= '9') ||
                   (c == KeyEvent.VK_BACK_SPACE) ||
                   (c == KeyEvent.VK_DELETE)))
                   {
                   getToolkit().beep();
                   e.consume();
                   }*/
                   //}
                //}
             			
              }}}
          
              class Finance 
             { 
                private int income; 
                private int bills; 
             
                private int max; 
                private double taxRate; 
             
                 public Finance(int max, double taxRate) 
                { 
                   setMax(max); 
                   this.taxRate = (taxRate >= 0.0 && taxRate <= 1.00) ? taxRate : 0.0; 
                } 
             
                 private void setMax(int max) 
                { 
                   this.max = (max >= 0) ? max : 0; 
                } 
             
                 public void setIncome(int income) 
                { 
                
                   if (income <= 0) 
                      this.income = 0; 
                   else if (income >= max) 
                      this.income = max; 
                   else 
                      this.income = income; 
                } 
             
                 public void setBills(int bills) 
                { 
                   if (bills <= 0) 
                      this.bills = 0; 
                   else if (bills >= max) 
                      this.bills = max; 
                   else 
                      this.bills = bills; 
                } 
             
                 public int getBills() 
                { 
                   return bills; 
                } 
             
                 public int getIncome() 
                { 
                   return income; 
                } 
             
                 public int getTax() 
                { 
                   return (int)(income * taxRate); 
                } 
             
                 public int getNet() 
                { 
                   return income - getTax() - bills; 
                } 
             } 
          
          }
       }
    Last edited by globo; 11-08-2010 at 09:03 PM.

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Have you tried using a DocumentFilter? That may work best for this problem. Check the Swing tutorials and search this forum for examples.

    e.g.: Limit number of cols in JTextArea (again)
    Last edited by Fubarable; 11-08-2010 at 09:10 PM.

  15. #15
    globo is offline Member
    Join Date
    Sep 2010
    Posts
    61
    Rep Power
    0

    Default

    it's more complicated than that in the example you provided. I need to get the text and automatically it gets updated in other field and when delete the text the deletion happens in other fields too. The backspace has to be in there.

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    globo, I moved your post from the linked thread back to this thread. Please try to avoid hijacking other threads. Thanks.

  17. #17
    globo is offline Member
    Join Date
    Sep 2010
    Posts
    61
    Rep Power
    0

    Default

    This is my thread.

  18. #18
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by globo View Post
    it's more complicated than that in the example you provided. I need to get the text and automatically it gets updated in other field and when delete the text the deletion happens in other fields too. The backspace has to be in there.
    The DocumentFilter would take care of preventing non-numeric entry and in fact you could make sure that what is entered is a valid int. Using a DocumentFilter would not prevent you from using a DocumentListener if you want to act on changes to the text component's document.

  19. #19
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by globo View Post
    This is my thread.
    I know that. You posted your previous reply in my linked thread. The only reason it's back here is because I moved it here.

  20. #20
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Though I have to ask you why all the complexity? Perhaps you're making things too difficult for no good reason. Why not simply have the user press a button, validate all input at that time? if the input is valid, do the calculations and display them, and if not, clear the fields and display a warning via JOptionPane.showMessageDialog.

Page 1 of 2 12 LastLast

Similar Threads

  1. Finding a number in array close to another number
    By SteroidalPsycho in forum New To Java
    Replies: 2
    Last Post: 02-15-2010, 12:37 AM
  2. Printing the Number of Times a Number in a Range Shows up
    By space4rent00 in forum New To Java
    Replies: 1
    Last Post: 02-05-2010, 10:42 PM
  3. Replies: 1
    Last Post: 08-07-2009, 12:14 PM
  4. checking for an event during an event
    By infinity in forum AWT / Swing
    Replies: 22
    Last Post: 04-09-2009, 01:08 AM
  5. Replies: 1
    Last Post: 11-03-2008, 02:38 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •