If user enters anything other than 0-9 or + - / * in the JtextField then a JOptionPane display error to user.
I seen a few different ways of potentially doing this...
Maybe a documentListener or a Inputverifyer.
Main Class
package p2gui;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.*;
import javax.swing.JOptionPane;
/**
*
*
*/
public class P2GUI extends JFrame implements ActionListener {
JFrame f = new JFrame("Three Address Generator");// Title
private final JButton evaluate;
private final JLabel textfieldLabel;
private final JTextField entryField;
private final JLabel resutfieldlabel;
private final JTextField resultField;
private final JOptionPane popup = new JOptionPane();
public void display() {
setVisible(true);
}
P2GUI() {
f.setSize(425, 180);//450 width and 525 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible //window size
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textfieldLabel = new JLabel("Enter Postfix Expression");
f.add(textfieldLabel);
textfieldLabel.setBounds(10, 10, 160, 25);
entryField = new JTextField("");
entryField.addActionListener(this);//ActionListener
f.add(entryField);
entryField.setBounds(160, 10, 220, 25);
evaluate = new JButton("Construct Tree");//creating instance of JButton
evaluate.addActionListener(this);//ActionListener
f.add(evaluate);
evaluate.setBounds(137, 55, 130, 30);
resutfieldlabel = new JLabel(" Infix Expression ");
f.add(resutfieldlabel);
resutfieldlabel.setBounds(20, 100, 100, 25);
resultField = new JTextField("");
resultField.addActionListener(this);//ActionListener
resultField.setEditable(false);
f.add(resultField);
resultField.setBounds(125, 100, 220, 25);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == evaluate) {
String fullString = entryField.getText().trim();
if (fullString.matches("\\d+") || fullString.matches("[-+*/]")) {
Convert conversion = new Convert();
resultField.setText(conversion.convert(fullString));
eraseTextField();
}else {
JOptionPane.showMessageDialog(null,"Wrong input enter a digit or
arithmetic operator");
eraseTextField();
}
}
}
public void eraseTextField() {
entryField.setText("");
entryField.requestFocus();
}
public static void main(String[] args) {
P2GUI p1GUI;
p1GUI = new P2GUI();
}
}
Convert. java class
package p2gui;
import java.util.Stack;
/**
*
* #author Mike
*/
public class Convert {
/**
* Checks if the input is operator or not
*
* #param c input to be checked
* #return true if operator
*/
private boolean operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
/**
* Converts any postfix to infix
*
* #param postfix String expression to be converted
* #return String infix expression produced
*/
public String convert(String postfix) {
Stack<String> s = new Stack<>();
for (int i = 0; i < postfix.length(); i++) {
char c = postfix.charAt(i);
if (operator(c)) {
String b = s.pop();
String a = s.pop();
s.push("(" + a + c + b + ")");
} else {
s.push("" + c);
}
}
return s.pop();
}
}
You can use regex to solve your problem, here is a simple example you can use it to solve your problem :
String str = "123";
if (str.matches("\\d+")) {
JOptionPane.showMessageDialog(null, "Degit");
} else if (str.matches("[-+*/]")) {
JOptionPane.showMessageDialog(null, "arithmetic operator( + - * /)");
}else{
JOptionPane.showMessageDialog(null, "Incorrect input");
}
Explication
str.matches("[-+*/]") if your input is - + * or / then it will return true.
str.matches("\\d+") if your input is a number then it will return true
You can use String.matches() to validate the expression entered by the user.
So basic code for this :
String expression = "9+45-3/5*9"; //store expression here from text-field.
boolean isvalid = expression.matches("[0-9-+*/]+");
if(isvalid)
JOptionPane.showMessageDialog(null,"Valid Expression!");
else
JOptionPane.showMessageDialog(null,"Not Valid Expression!");
Still here you need to check other requirements that no two operators comes continuously and other stuff as well.
Not sure if I need to edit this class or not since the cards ARE changing. Just not in order
import java.lang.Integer;
/**
* This class is used to keep track of playing cards.
*
* #author (name)
* #version (date)
*/
public class Card implements Comparable<Card>
{
public int compareTo(Card otherCard) {
// instance variables - replace the example below with your own
private String denom, suit;
/**
* Card is to be passed in as a denomination and suit
*/
public Card(String description)
{
description = description.toUpperCase();
if( description.length() == 2)
{
suit = description.substring(1);
denom = description.substring(0,1);
} else if(description.length() == 3) {
suit = description.substring(2);
denom = description.substring(0,2);
} else {
System.out.print("Error: An invalid card code was given.");
}
}
/**
* This will give a string that states a description of the card.
* #return Card description as a string.
*/
public String getDis()
{
//get the description
String denomMessage = denom;
if(denom.equals("A"))
denomMessage = "Ace";
else if(denom.equals("K"))
denomMessage = "King";
else if(denom.equals("Q"))
denomMessage = "Queen";
else if(denom.equals("J"))
denomMessage = "Jack";
//get the suit
String suitMessage = suit;
if(suit.equals("S"))
suitMessage = "Spades";
else if(suit.equals("D"))
suitMessage = "Dimonds";
else if(suit.equals("C"))
suitMessage = "Clubs";
else if(suit.equals("H"))
suitMessage = "Hearts";
else
suitMessage = "There was a problem";
return denomMessage + " of " + suitMessage;
}
/**
* This was written for the purpose of helping to select a card image.
* #return clubs are 1, hearts are 2, spades are 3, diamonds are 4
*/
public int numSuit()
{
int value = 0;
if(suit.equals("C"))
value = 1;
else if(suit.equals("H"))
value = 2;
else if(suit.equals("S"))
value = 3;
else if(suit.equals("D"))
value = 4;
return value;
}
/**
* This class was written for the purpose of selecting a card image
* #return ace is a 1, jack is a 11, queen is a 12, king is a 13
*/
public int numDenom()
{
int value = 0;
if(denom.equals("A"))
value = 1;
else if(denom.equals("J"))
value = 11;
else if(denom.equals("Q"))
value = 12;
else if(denom.equals("K"))
value = 13;
else
value = Integer.parseInt(denom);
return value;
}
/**
* Are the two cards the same suit and denomination?
* #return true or false
*/
public boolean equals(Card a)
{
if(denom.equals(a.denom) && suit.equals(a.suit))
return true;
else
return false;
}
/**
* I would suggest that you write this method
*/
public int denomCompareTo(Card a)
{
return a.numDenom() - numDenom();
}
}
All it's doing is changing it's card to the lowest card entered. I have to make it go in order from smallest to largest. no matter what face.
import java.awt.*;
import java.io.*;
import java.applet.*;
import java.awt.image.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* This applet is currently working. It will run in a webpage. It will take in card codes such as
* 2h for the two of heart and "paint" the image of five cards when all five text fields each have a
* card coding entered into them. Your assignment will be to write the part of the code
* that will sort the cards once they have been entered so that the will be "painted" from smallest
* to largest denomination regardless of suit as long "None" is selected in the drop down box. In
* the event one of the suits is selected that suit will be placed in order first then followed by
* the rest of the cards in order. To complete the assignment you should read through this class' code
* but you will only need to change the section that state that you should change it and possibly
* the card class.
*
* #author (Put your name here.)
* #version (Put the date here.)
*/
public class CardApplet extends Applet {
Image ic1,ic2,ic3,ic4,ic5;
Card c1,c2,c3,c4,c5;
private TextField cardIn1,cardIn2,cardIn3,cardIn4,cardIn5;
private String message;
private Button enter,sort;
private ButtonListener buttonListen;
private Choice trump;
static final int CARD_WIDTH = 73;
static final int CARD_HEIGHT = 98;
/**
* This is called an inner class as it is a class writen inside of another class. It is here so
* that the buttons will be able to trigger an event.
*/
class ButtonListener implements ActionListener
{
/**
* The name of this method is important and should not be changed. This will take in the
* "action" of a button being pushed and store reference to it in the object variable e.
*/
public void actionPerformed(ActionEvent e)
{
String action = e.paramString();
if( action.indexOf("Enter") >= 0)
{
//get text
String text1 = cardIn1.getText();
String text2 = cardIn2.getText();
String text3 = cardIn3.getText();
String text4 = cardIn4.getText();
String text5 = cardIn5.getText();
//Get rid of whitespace before and after string
text1 = text1.trim();
text2 = text2.trim();
text3 = text3.trim();
text4 = text4.trim();
text5 = text5.trim();
message = "Cards Entered";
//setup cards and card images
c1 = new Card(text1);
ic1 = getCardImage(c1);
c2 = new Card(text2);
ic2 = getCardImage(c2);
c3 = new Card(text3);
ic3 = getCardImage(c3);
c4 = new Card(text4);
ic4 = getCardImage(c4);
c5 = new Card(text5);
ic5 = getCardImage(c5);
//this method call is to this class and tells the applet to follow the code of paint again.
repaint();
}
else if( action.indexOf("Sort") >= 0)
{
//ADD YOUR CODE HERE.
if(c1.denomCompareTo(c2) < 0 )
ic1 = ic2;
c1 = c2;
if(c1.denomCompareTo(c3) < 0 )
ic1 = ic3;
c1 = c3;
if(c1.denomCompareTo(c4) < 0 )
ic1 = ic4;
c1 = c4;
if(c1.denomCompareTo(c5) < 0 )
ic1 = ic5;
c1 = c5;
if(c2.denomCompareTo(c1) < 0 )
ic2 = ic1;
c2 = c1;
if(c2.denomCompareTo(c3) < 0 )
ic2 = ic3;
c2 = c3;
if(c2.denomCompareTo(c4) < 0 )
ic2 = ic4;
c2 = c4;
if(c2.denomCompareTo(c5) < 0 )
ic2 = ic5;
c2 = c5;
if(c3.denomCompareTo(c1) < 0 )
ic3 = ic1;
c3 = c1;
if(c3.denomCompareTo(c2) < 0 )
ic3 = ic2;
c3 = c2;
if(c3.denomCompareTo(c4) < 0 )
ic3 = ic4;
c3 = c4;
if(c3.denomCompareTo(c5) < 0 )
ic3 = ic5;
c3 = c5;
if(c4.denomCompareTo(c1) < 0 )
ic4 = ic1;
c4 = c1;
if(c4.denomCompareTo(c2) < 0 )
ic4 = ic2;
c4 = c2;
if(c4.denomCompareTo(c3) < 0 )
ic4 = ic3;
c4= c3;
if(c4.denomCompareTo(c5) < 0 )
ic4 = ic5;
c4 = c5;
if(c5.denomCompareTo(c1) < 0 )
ic5 = ic1;
c5 = c1;
if(c5.denomCompareTo(c2) < 0 )
ic5 = ic2;
c5 = c2;
if(c5.denomCompareTo(c3) < 0 )
ic5 = ic3;
c5 = c3;
if(c5.denomCompareTo(c4) < 0 )
ic5 = ic4;
c5 = c4;
//DO NOT CHANGE CODE PAST THIS LINE.
message = "Sorted";
repaint();
}
}
} //end of inner class.
/**
* This method is called when the applet is first started. It will setup the layout of the applet.
*/
public void init() {
//This is the text that prints in the gray box towards the bottem of the applet.
message="Let us get started ";
//Sets the back ground color of the the applet
setBackground(Color.GREEN);
// Set default layout manager
setLayout(new FlowLayout() );
//setup textboxes for entering in cards
cardIn1 = new TextField("Enter",4);
add(cardIn1);
cardIn2 = new TextField("cards ",4);
add(cardIn2);
cardIn3 = new TextField("using",4);
add(cardIn3);
cardIn4 = new TextField("Chap 5",4);
add(cardIn4);
cardIn5 = new TextField("coding",4);
add(cardIn5);
//place buttons
buttonListen = new ButtonListener();
enter = new Button("Enter");
enter.addActionListener(buttonListen);
add(enter);
sort = new Button("Sort");
sort.addActionListener(buttonListen);
add(sort);
//setup dropdown
trump = new Choice();
trump.addItem("None");
trump.addItem("Hearts");
trump.addItem("Diamonds");
trump.addItem("Spades");
trump.addItem("Clubs");
add(trump);
//Since the card object variables are null each image object variable
//will hold reference to a card back image.
ic1 = getCardImage(c1);
ic2 = getCardImage(c2);
ic3 = getCardImage(c3);
ic4 = getCardImage(c4);
ic5 = getCardImage(c5);
}
/*
* This class is used to place graphics on an applet.
*/
public void paint(Graphics g) {
//places cards on applet
int linePos = 70;
g.drawImage(ic1,19,linePos,this);
g.drawImage(ic2,19+CARD_WIDTH,linePos,this);
g.drawImage(ic3,19+2*CARD_WIDTH,linePos,this);
g.drawImage(ic4,19+3*CARD_WIDTH,linePos,this);
g.drawImage(ic5,19+4*CARD_WIDTH,linePos,this);
// simple text displayed on applet
g.setColor(Color.lightGray);
g.draw3DRect(2, 175, 200, 20, true);
g.fillRect(2, 175, 200, 20);
g.setColor(Color.black);
g.drawString(message, 4, 190);
}
/**
* This will select either the correct portion of the cards image based on the suit and denomination or
* the card back image.
* #param a The card object holds the suit and denomination in state.
* #return It returns an image object variable with holds reference to a image that was created for a card that was passed in.
* #throws MalformedURLException
*/
public Image getCardImage(final Card a)
{
int cardDenom,cardSuit;
Image playingCards = null;
ImageFilter cardFilter;
ImageProducer cardProducer;
if( a == null)
{
playingCards = getImage(getCodeBase(), "cardBack.png");
}else{
playingCards = getImage(getCodeBase(),"cards.png");
cardDenom = (a.numDenom()*CARD_WIDTH)- CARD_WIDTH;
cardSuit = (a.numSuit()*CARD_HEIGHT) - CARD_HEIGHT;
cardFilter = new CropImageFilter(cardDenom,cardSuit,CARD_WIDTH,CARD_HEIGHT);
cardProducer = new FilteredImageSource(playingCards.getSource(),cardFilter);
playingCards = createImage(cardProducer);
}
return playingCards;
}
}
nIcE cOw is correct in mentioning Comparable
from http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Which means that your implementation of Comparable for your objects (cards) should follow that convention.
In your top code section
public int denomCompareTo(Card a)
{
if ( a.numDenom() < this.numDenom() ) //the value of card a is less
{ return -1; }
else if ( a.numDenom() == this.numDenom() ) //equality
{ return 0; }
else //otherwise.. whatever's left (a must be greater)
{ return 1;}
}
Read that over until you understand it. Comparable is the method you want to definitely work. It's going to be invoked by calling
FirstCard.CompareTo( SecondCard );
that line of code is going to return a value of either -1, 0, or 1. Depending on which is greater, or 0 if they are equal. That's all a sorting algorithm really /needs/ to be able to figure out an ordering.
So that's the code you need for Comparable. Please look it over until you understand it.
The code in the second portion,
else if( action.indexOf("Sort") >= 0)
{
//ADD YOUR CODE HERE.
...
}
Needs to be updated to reflect how Comparable works.
So I am guessing this is a button or action thingy, and if you specify Sort then we want to sort the cards. Fair enough. Well, where are the cards stored? It looks like in a bunch of variables named c(number) and ic(number) for the image. Like c1 and ic1, c2 and ic2. In the future, look into using arrays.
So your code is almost correct for this portion! It's just that you need a temporary value to store the old card. Otherwise you're overwriting it everytime.
For example: First basket is an apple, Second basket is a grape.
If you say "Hey, put the contents of the 2nd basket into the 1st" then the first one becomes grape. The second one is also (still) grape. Where did apple go? We lost it because computers are mercilessly true to your instructions. We need to store the old card in a new variable.
So when you say
if(c1.denomCompareTo(c2) < 0 ) { //for the love of jobe please use braces for multiline if statements
ic1 = ic2;
c1 = c2;
}
The original ic1 and c1 are being overwritten and lost.
You can fix this by using a temporary variable or swapping variable, or when you get really clever, using XOR (ask your nerdy friends)
Image tempImg;
Card tempCard;
if(c1.denomCompareTo(c2) < 0 ) { //meaning if card1 is less than card2
tempImg = ic1; //store card1 temporarily
tempCard = c1;
ic1 = ic2; //copy vals of card2 to card1 slots
c1 = c2;
ic2 = tempImg; //slide the original val of ic1 here
c2 = tempCard;
}
Granted, your sorting algorithm is accurate, but will require many passes if the cards are in any funky ordering. Which is why you'll probably have to loop over these instructions several times. You're doing something incrementally usually referred to as "bubble sort" ... If you need help looping over your sorting, just let us know.
Here are some examples:
I am posting a very quick reference example for you to look at. It is not that tough to understand, though, once you will understand it, things will become a bit more easier.
import java.util.*;
enum Suit {
HEART,
DIAMOND,
CLUB,
SPADE
}
class Card implements Comparable<Card> {
private int rank;
private Suit suit;
public Card ( int rank, Suit suit ) {
this.rank = rank;
this.suit = suit;
}
public int getRank () {
return rank;
}
public void setRank ( int rank ) {
this.rank = rank;
}
public Suit getSuit () {
return suit;
}
public void setSuit ( Suit suit ) {
this.suit = suit;
}
#Override
public int compareTo ( Card anotherCard ) {
return this.rank - anotherCard.rank;
}
#Override
public String toString () {
return String.format ("Suit: %8s Rank: %8s", suit, rank);
}
}
public class CardsExample {
private static final int TOTAL_CARDS = 52;
private static final int CARDS_PER_SUIT = 13;
private static final int TOTAL_SUITS = 4;
private List<Card> deck;
public CardsExample () {
deck = new ArrayList<Card> ();
}
private void createDeck () {
for ( Suit suit : Suit.values () ) {
for ( int i = 0; i < CARDS_PER_SUIT; ++i ) {
deck.add ( new Card ( i, suit ) );
}
}
}
private void displayDeck () {
for ( Card card : deck ) {
System.out.println ( card );
}
}
private void performTask () {
createDeck ();
Collections.shuffle ( deck );
System.out.println ( "Before SORTING" );
displayDeck ();
Collections.sort ( deck );
System.out.println ( "After SORTING" );
displayDeck ();
}
public static void main ( String[] args ) {
new CardsExample ().performTask ();
}
}
EDIT:
If one wants to sort cards, in terms of their Suit first, then one can use Comparatortoo, in this example, for which not much of a change is required, just change the enum part, as shown below and provide implementation for Comparator < Card >, within the Cardclass, and let Collections.sort ( deck, suitComparator )do the work, as shown in this example.
import java.util.*;
enum Suit {
HEART ( 0 ),
DIAMOND ( 1 ),
CLUB ( 2 ),
SPADE ( 3 );
private int value;
private Suit ( int value ) {
this.value = value;
}
public int retrieveValue () {
return value;
}
}
class Card implements Comparable < Card > {
private int rank;
private Suit suit;
public static Comparator < Card > suitComparator =
new Comparator < Card > () {
#Override
public int compare ( Card someCard, Card anotherCard ) {
return someCard.suit.retrieveValue () - anotherCard.suit.retrieveValue ();
}
};
public Card ( int rank, Suit suit ) {
this.rank = rank;
this.suit = suit;
}
public int getRank () {
return rank;
}
public void setRank ( int rank ) {
this.rank = rank;
}
public Suit getSuit () {
return suit;
}
public void setSuit ( Suit suit ) {
this.suit = suit;
}
#Override
public int compareTo ( Card anotherCard ) {
return this.rank - anotherCard.rank;
}
#Override
public String toString () {
return String.format ( "Suit: %8s Rank: %8s", suit, rank );
}
}
public class CardsExample {
private static final int TOTAL_CARDS = 52;
private static final int CARDS_PER_SUIT = 13;
private static final int TOTAL_SUITS = 4;
private List < Card > deck;
public CardsExample () {
deck = new ArrayList < Card > ();
}
private void createDeck () {
for ( Suit suit : Suit.values () ) {
for ( int i = 0; i < CARDS_PER_SUIT; ++i ) {
deck.add ( new Card ( i, suit ) );
}
}
}
private void displayDeck () {
for ( Card card : deck ) {
System.out.println ( card );
}
}
private void performTask () {
createDeck ();
Collections.shuffle ( deck );
System.out.println ( "Before SORTING" );
displayDeck ();
Collections.sort ( deck );
Collections.sort ( deck, Card.suitComparator );
System.out.println ( "After SORTING" );
displayDeck ();
}
public static void main ( String[] args ) {
new CardsExample ().performTask ();
}
}
Good luck
I am creating a Combination Lock class in Netbeans and I am confused as to why when I run the file I do not recieve any output. Anyone know what I am doing wrong? Any and all help would be greatly appreciated! Here is the code in my constructer class :
package combinationlock ;
/**
* A class to implement a combination lock with 26 dial positions
* and a three-letter combination
*
* #Carlos
*/
public class CombinationLock
{
// instance variable declarations go here
private boolean open ;
private int Count ;
private String position1 ;
private String position2 ;
private String position3 ;
private String first = "F" ;
private String second = "I" ;
private String third = "U" ;
/**
* Creates a lock with a given combination consisting of three upper-case characters.
* #param first the first letter of the combination
* #param second the second letter of the combination
* #param third the third letter of the combination
*/
public CombinationLock(String first, String second, String third)
{
this.first = first ;
this.second = second ;
this.third = third ;
open = false ;
Count = 0 ;
}
/**
* Set the dial to a position
* #param aPosition a String consisting of a single uppercase letter (A..Z)
*/
public void setPosition(String aPosition)
{
if (Count == 0)
{
position1 = aPosition ;
Count = Count + 1 ;
}
else if (Count == 1)
{
position2 = aPosition ;
Count = Count + 1 ;
}
else if (Count == 2)
{
position3 = aPosition ;
}
}
/**
* Try opening the lock
*/
public void tryToOpen()
{
if (first.equals(position1) && second.equals(position2) && third.equals(position3))
{
open = true ;
System.out.println("Its open!") ;
}
else
{
open = false ;
System.out.println("Wrong combination! Please try again.") ;
}
}
/**
* Check whether the lock is open
* #return true or false indicating whether the lock is open
*/
public boolean isOpen()
{
return open ;
}
/**
* Close the lock and print a message indicating that the lock is now closed
*/
public void lock()
{
Count = 0 ;
open = false ;
System.out.println("You re-apply the lock") ;
}
}
And here is the code I used in my tester class:
package combinationlock ;
import javax.swing.JOptionPane ;
/**
*
* #author Carlos
*/
public class CombinationLockTester
{
public static void main (String[] args)
{
CombinationLock MasterLock = new CombinationLock("A", "B", "C");
String input = JOptionPane.showInputDialog
("Please enter first letter.") ;
MasterLock.setPosition(input) ;
String input2 = JOptionPane.showInputDialog
("Please enter second letter.") ;
MasterLock.setPosition(input2) ;
String input3 = JOptionPane.showInputDialog
("Please enter third letter") ;
MasterLock.setPosition(input3);
System.out.println("The combination entered was " +input + input2 +input3) ;
}
}
You are setting positions on MasterLock but not calling the tryToOpen method. Try this and see if you get any output:
MasterLock.tryToOpen();
Which should be called after the three calls to setPosition.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Restricting JTextField input to Integers
Detecting JTextField “deselect” event
i need to validate a JTextField by allowing the user to input only integer values in it if user enters any char other than numbers a JOptionPane.show messagebox should appear showing that the value entered are incorrect and only integer numbers are allowed. I have coded it for a digit values but i also need to discard the alphabets
public void keyPressed(KeyEvent EVT) {
String value = text.getText();
int l = value.length();
if (EVT.getKeyChar() >= '0' && EVT.getKeyChar() <= '9') {
text.setEditable(true);
label.setText("");
} else {
text.setEditable(false);
label.setText("* Enter only numeric digits(0-9)");
}
}
Instead of using a JFormattedTextField, you may write a custom JTextField with a document that allows only integers. I like formatted fields only for more complex masks...
Take a look.
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 );
}
}
}
If you are using NetBeans to build your GUI, you just need to put regular JTextFields in your GUI and in the creation code, you will specify the constructor of IntegerField.
There is a componant for that: formatted textfield:
http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html
Use JFormattedTextField capabilities. Have a look at example.
I have two textfield in my swing component. In one text field i need to have only numbers
(no string,empty spaces,special charaters allowed) and in another textfield i need to have only string(no numbers,empty spaces,special charaters allowed). How can i implement that..???
You can use the Pattern Class (Regular Expressions) to validate the input. A short tutorial is available here.
I am pretty sure that the basic tutorial covers all this...
"^//d+$" //The text must have at least one digit, no other characters are allowed
"^[a-zA-Z]+$" //The text must have at least one letter, no other characters are allowed
You have two choices, you can validate the text in the fields either 1) on entry or 2) when the user performs an action such as clicks a confirmation button.
For 2) npinti's answer should steer you in the right direction, just get the value of the field and validate it with a regular expression.
For 1) you might want to write a KeyListener that intercepts key presses and only allows the correct type of character for the field.
You can extend javax.swing.text.PlainDocument class, and call setDocument method textfield. Here is one of the example ;
package textfield;
import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class LimitedValuePositiveIntegerDocument extends PlainDocument {
int maxValue;
int maxLength;
Toolkit toolkit;
/**
* Constructor for the class.
* #param max maximum value of the number
*/
public LimitedValuePositiveIntegerDocument(int max){
maxValue = max;
maxLength = (""+max).length();
toolkit = Toolkit.getDefaultToolkit();
}
/**
* Inserts the input string to the current string after validation.
* #param offs offset of the place where the input string is supposed to be inserted.
* #param str input string to be inserted
* #param a attribute set
*/
#Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if(str == null)return;
String currentText = getText(0,getLength());
String resultText = new String();
int i;
boolean errorFound = false;
boolean deleteFirstZero = false;
int accepted=0;
for (i = 0; (i<str.length())&&(!errorFound); i++) {
if (Character.isDigit(str.charAt(i))) { /* if it is digit */
if (offs==currentText.length()) { /* calculates the resultant string*/
resultText = currentText+str.substring(0,i+1);
} else if (offs==0) {
resultText = str.substring(0,i+1)+currentText;
} else {
resultText = currentText.substring(0, offs)+str.substring(0,i+1)+currentText.substring(offs,currentText.length());
}
if (Integer.parseInt(resultText) > maxValue) {
errorFound = true;
toolkit.beep();
} else {
if ( resultText.length() == maxLength+1) {
deleteFirstZero = true;
}
accepted++;
}
} else {
errorFound = true;
toolkit.beep();
}
}
if ( accepted>0 ) { /* insert string */
super.insertString(offs, str.substring(0,accepted), a);
if (deleteFirstZero) {
super.remove(0,1);
}
}
}
/**
* Removes a part of the current string.
* #param offs offset of the place to be removed.
* #param len length to be removed
*/
#Override
public void remove(int offs, int len) throws BadLocationException{
super.remove(offs, len);
}
/**
* Returns max value of the number.
* #return max value
*/
public int getMaxValue() {
return maxValue;
}
/**
* Sets max value of the number.
* #param max maximum value of the number
*/
public void setMaxValue(int max) {
this.maxValue = max;
}
} // end of class
EDIT :
and its usage;
LimitedValuePositiveIntegerDocument doc = new LimitedValuePositiveIntegerDocument(999);
JTextField numberField = new JtextField();
numberField.setDocument(doc);
You can only enter positive numbers less than 1000, and it check while you are pressing the key..