Results 1 to 20 of 24
Thread: Key event + only number
- 11-04-2010, 05:40 PM #1
Member
- Join Date
- Sep 2010
- Posts
- 61
- Rep Power
- 0
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; } }
- 11-04-2010, 05:44 PM #2
- 11-04-2010, 05:48 PM #3
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,383
- Blog Entries
- 7
- Rep Power
- 17
- 11-04-2010, 05:50 PM #4
Senior Member
- Join Date
- Dec 2009
- Posts
- 104
- Rep Power
- 0
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 :PBeginner in Java Programming, Please don't trust my anwsers blind please :D
- 11-04-2010, 05:52 PM #5
Member
- Join Date
- Sep 2010
- Posts
- 61
- Rep Power
- 0
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.
- 11-04-2010, 05:55 PM #6
And what was wrong with the answer(s) you received?
- 11-04-2010, 05:58 PM #7
Member
- Join Date
- Sep 2010
- Posts
- 61
- Rep Power
- 0
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.
- 11-04-2010, 06:00 PM #8
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.
- 11-04-2010, 06:06 PM #9
Member
- Join Date
- Sep 2010
- Posts
- 61
- Rep Power
- 0
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?
- 11-04-2010, 06:08 PM #10
Member
- Join Date
- Sep 2010
- Posts
- 61
- Rep Power
- 0
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-04-2010, 06:46 PM #11
- 11-04-2010, 06:47 PM #12
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)
- 11-08-2010, 09:00 PM #13
Member
- Join Date
- Sep 2010
- Posts
- 61
- Rep Power
- 0
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.
-
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.
- 11-08-2010, 10:40 PM #15
Member
- Join Date
- Sep 2010
- Posts
- 61
- Rep Power
- 0
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.
-
globo, I moved your post from the linked thread back to this thread. Please try to avoid hijacking other threads. Thanks.
- 11-08-2010, 10:53 PM #17
Member
- Join Date
- Sep 2010
- Posts
- 61
- Rep Power
- 0
This is my thread.
-
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.
-
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.
-
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.
Similar Threads
-
Finding a number in array close to another number
By SteroidalPsycho in forum New To JavaReplies: 2Last Post: 02-15-2010, 12:37 AM -
Printing the Number of Times a Number in a Range Shows up
By space4rent00 in forum New To JavaReplies: 1Last Post: 02-05-2010, 10:42 PM -
Geting Mobile Number, Mobile Operator, Location and Mobile Serial Number by J2ME.
By maruffaiz in forum CLDC and MIDPReplies: 1Last Post: 08-07-2009, 12:14 PM -
checking for an event during an event
By infinity in forum AWT / SwingReplies: 22Last Post: 04-09-2009, 01:08 AM -
how to extract the number of the image which looks like a number
By Crest.Boy in forum Java ServletReplies: 1Last Post: 11-03-2008, 02:38 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks