can't solve this problem.
I want to retrieve the text that I write on my textfield with keyTyped and put int on a String. But If I do it, it gives me a blank String. What can I do?
textField_9.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e){
xw = textField_9.getText(); //should retrieve my input
}
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if((!(Character.isDigit(c)) && (c!='.'))){
e.consume();
}
System.out.println(xw); //gives nothing ("") not null
numero = e.getKeyChar();
String fileName = defaultx+"\\"+"Contratti"+"\\"+textField_7.getText()+"\\"+"lista"+tipo;
Scanner scanner;
try {
scanner = new Scanner(new File(fileName));
scanner.useDelimiter(":");
while(scanner.hasNext()){
num = scanner.next();
System.out.println("Numero = "+num+"\t"+xw); //debug
dat = scanner.nextLine().replaceAll(":", "");
if(num == xw){
try(Scanner scanner1 = new Scanner(dat)){
scanner1.useDelimiter(":");
giorno = scanner1.next();
meset = scanner1.next();
anno = scanner1.next();
System.out.println(giorno+"-"+meset+"-"+anno); //debug
}catch(NoSuchElementException ex){
}
}else{
System.out.println("Dato non trovato");
}
}
scanner.close();
} catch (FileNotFoundException e1) {
} catch(NoSuchElementException e1){
}
}
});
Example
I write into my JTextField the number "5" , xw should be then "5" but instead it will be ""
Basically what I'm trying to do is to read user's input, this input (that's a number) will be searched in a .txt file that contains a list of number and dates. example : 1st line of the .txt file is "1:1-01-2017" the second line is 2:8-01-2017" the third line is "3:15:01:2017 etc..
Read this data in once not with each key press as you're trying to do above, perhaps doing this in the class's constructor. Then store the data in a searchable collection, perhaps an array list of custom class.
so what I want to do is to search in this .txt file that number before ":" and when it finds it ,write in another textfield the date. example. user write in textfield1 "3", the program will search in the .txt file the number 3 that is before the ":" and when it find it , will write the date into another textfield.
The custom class that holds the text file's data should hold the separate numbers in their own fields, and again, search the ArrayList of these objects when needed.
Also:
do not add a KeyListener to a JTextField as this can prevent the JTextField from behaving correctly (as you're finding out).
We sometimes add a DocumentListener or a DocumentFilter to the JTextField's Document for similar behaviors...
But in your case I wouldn't do either. Instead add an ActionListener to the JTextField, a listener which is activated when the ENTER key is pressed, and search the ArrayList from within this listener.
You should almost never have empty catch blocks as we see in your code above. At least print out the stacktrace, as you could very well be having problems from exceptions being thrown completely without your knowledge since your code ignores them.
Related
I am building a GUI for some Java project. I need to validate what user input on JTextField. But I have a small problem.
The JTextField is for entering Integer. So, I did try and catch for NumberFormatException. The question is: if the user fires an action (press Enter) without writing anything in the JTextField even space, How could I handle this?
int id = 0;
try {
id = Integer.parseInt(tfID.getText());
} catch (NumberFormatException e1 ) {
if (tfID.getText()==null) //This does not work
idError.setText("Enter an Integer");
else
idError.setText("Intgers only accepted");
}
I want to show a message on another JTextfield (which is idError in this case) to tell the user to enter an Integer.
Thanks in advance.
Instead of using:
if (tfID.getText()==null)
use:
if( tfID.getText().equals("") )
which will return true if and only if the two strings are equal, which is here tfID.getText() and ("").
Thanks for you all.
So I'm writing a car loan amortization GUI program. The end goal is to get either user input data or input from a file and display the payment schedule. I have the user input schedule displaying to the console window for now but my main question is how do I store the data from the text file into variables in order to plug them into the equation?
I am using scanner and stringbuilder and am able to display the contents of the file in the console window, but can't figure out how to store the values into variables. Also if anyone has any tips as to how to display the schedule from the console window onto a second GUI, that would be nice as well.
File workingDir = new File(System.getProperty("user.dir"));
JFileChooser openfile = new JFileChooser();
openfile.setDialogTitle("Choose a file");
openfile.setCurrentDirectory(workingDir);
int status = openfile.showOpenDialog(null);
try {
if(status != JFileChooser.APPROVE_OPTION)
{
return null; // error
}
else {
File file = openfile.getSelectedFile();
Scanner scan = new Scanner(file);
StringBuilder info = new StringBuilder();
while (scan.hasNext()) {
String data = scan.nextLine();
System.out.println(data);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
}
return null;
}`
Your obviously not showing the actual method declaration for your sample code and by the look of it your data file only contains a single line so I'm just going to wing it here.
Everything within a text file is considered as String content. To convert the data within a text file you would need to use parsers. Your comma delimited file data line contains 3 specific values which would definitely benefit (for now) being of double data type. In order to segment this data line and place the value contents into double type variables you would need to use the String.split() method:
In my opinion I think it's just better to read each file line in its entirety by using hasNextLine() in conjunction with scan.NextLine() rather than hasNext():
while (scan.hasNextLine()) {
String data = scan.nextLine();
// Skip blank lines or possible comment lines
// (lines that start with a semi-colon).
if (data.trim().equals("") || data.trim().startsWith(";")) {
continue;
}
// Create an Array of string values.
String[] stringValues = data.split(", ");
}
This now creates a String Array with each element of that array containing the individual values that were contained on the file data line:
stringValues[0] will hold the string: 6500
stringValues[1] will hold the string: 4.5
stringValues[2] will hold the string: 6
Remember, Array indexing starts from 0 not 1. Now all that is needed is to convert and place these elements into individual double data type variables and we can do that like this.
double totalAmount = Double.parseDouble(stringValues[0]);
double interestAmount = Double.parseDouble(stringValues[1]);
double durationAmount = Double.parseDouble(stringValues[2]);
Your while loop could now possibly look like this:
double totalAmount = 0.0;
double interestAmount = 0.0;
double durationAmount = 0.0;
while (scan.hasNextLine()) {
String data = scan.nextLine();
// Skip blank lines or possible comment lines
// (lines that start with a semi-colon).
if (data.trim().equals("") || data.trim().startsWith(";")) {
continue;
}
// Create an Array of string values.
String[] stringValues = data.split(", ");
// Convert String Array elements to their
// respective double type variables.
totalAmount = Double.parseDouble(stringValues[0]);
interestAmount = Double.parseDouble(stringValues[1]);
durationAmount = Double.parseDouble(stringValues[2]);
}
// rest of code here.....
Now it's a matter of you using those double type variables as you see fit to carry out your calculations.
As for displaying a schedule within a GUI I would recommend the use of a JTable. Create your GUI and add a JTable. For now just have all cells accept String rather than specific data types. To add rows of data to your JTable you can use a method like this:
private void addRowToJTable(JTable table, Object[] rowData) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(rowData);
}
The Object Array you pass to this method would contain elements that represent each column of the table. A simple use case would be:
// Table Columns: Payment #, Pymt Date, Payment, Interest, Principle, Balance
Object[] rowData = {"1", "Jun 12, 2018", "$112.39", "$40.63", "$71.76", "$6,428.24"};
addRowToJTable(jTable1, rowData);
Of course you would have this code in a loop of some sort as you build your schedule. If you would like a runnable example application I quickly whipped up to demonstrate this stuff then send me an e-mail. Your example data line could produce a schedule that could look something like this:
Suppose I have 3 TextFields - used for users to input values into (when the program is running):
TextField input1 = new JTextField("00");
TextField input2 = new JTextField("00");
TextField input3 = new JTextField("00");
When the user inputs values, the program then takes those values and stores them as Integers (for operations later on):
public void actionPerformed(ActionEvent e) {
String temp1 = input1.getText();
String temp2 = input.getText();
String temp3 = input3.getText();
int num1=0, num2=0, num3=0;
if(e.getSource() == storeButton){
try{
num1 = Integer.parseInt(tem1);
num2 = Integer.parseInt(temp2);
num3 = Integer.parseInt(temp3);
}
catch(NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Input must be an integer from 0 to 50");
}
}
}
As the above code shows, when the user clicks the storeButton the values in the TextFields are parsed into the specific variables as integers and if any of the TextFields contain an input besides an integer, a message will pop up.
The question:
When the exception is called, how do I clear (set to "0") the TextField that does not contain a number? The TextFields that contain an integer must not be cleared.
I can do that by using try and catch for each of the TextFields when parsing as integers but that would mean too much repetition of code (especially when there are many TextFields).
Take a look at Character.isDigit(). You could make a sub-method that loops through each String and checks it to see if it is a digit.
Alternatively, you could use a regex on the String to check if it is a digit.
This lets you get rid of the try/catch and handle them with if/else.
I am having troubles in finding a solution to write a listener for a JTextField specifically to only allow integer values (No Strings allowed). I've tried this recommended link on Document Listener, but I don't know what method to invoke etc.
I've never used this type of Listener before, so could anyone explain how I could write a listener on a JTextField to only allow integer values that can be accepted?
Basically after I click a JButton, and before the data is extracted out onto a variable, then Listener will not allow it to be processed until an integer is inputted.
Thanks very much appreciated.
You don't want a listener, you want to get the text from the JTextField and test if it is an int.
if (!input.getText().trim().equals(""))
{
try
{
Integer.parseInt(myString);
System.out.println("An integer"):
}
catch (NumberFormatException)
{
// Not an integer, print to console:
System.out.println("This is not an integer, please only input an integer.");
// If you want a pop-up instead:
JOptionPane.showMessageDialog(frame, "Invalid input. Enter an integer.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
You could also use a regex (a little bit of overkill, but it works):
boolean isInteger = Pattern.matches("^\d*$", myString);
You don't want a document listener. You want an ActionListener on the submit/ok button.
Make sure that listener is created with a handle to the JTextField, then put this code in the actionPerformed call:
int numberInField;
try {
numberInField = Integer.parseInt(myTextField.getText());
} catch (NumberFormatException ex) {
//maybe display an error message;
JOptionPane.showMessageDialog(null, "Bad Input", "Field 'whatever' requires an integer value", JOptionPane.ERROR_MESSAGE);
return;
}
// you have a proper integer, insert code for what you want to do with it here
how I could write a listener on a JTextField to only allow integer values that can be accepted?
You should be using a JFormattedTextField or a Document Filter.
JFormattedTextField example:
public static void main(String[] args) {
NumberFormat format = NumberFormat.getInstance();
format.setGroupingUsed(false);
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMinimum(0);
formatter.setMaximum(Integer.MAX_VALUE);
JFormattedTextField field = new JFormattedTextField(formatter);
JOptionPane.showMessageDialog(null, field);
}
JFormattedTextField works well for restricting input. In addition to limiting input to numbers, it is capable of more advanced use, e.g. phone number format. This provides immediate validation without having to wait for form submission or similar event.
In my program, I have a JTextField reading the user input. The user is supposed to enter a number and then click a JButton to confirm the entry, but i want to have a catch where if the user does not enter a number, a pop-up appears telling the user it is an incorrect input. How would I implement something to detect whether or not the user enters a number when the JButton is clicked? if i need to give more code, let me know.
JButton okay = new JButton("OK");
JTextField dataEntry = new JTextfield();
okay.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
firstEntry = Float.parseFloat(dataEntry.getText());
//want to see if it's a float, if true, run the following code
confirm = true;
changeText();
dataEntry.setText("");
}
});
parseFloat throws a NumberFormatException if the passed String does not contain a parseable float. You can catch this exception to detect whether the user has entered a float:
try {
firstEntry = Float.parseFloat(dataEntry.getText());
} catch (NumberFormatException e) {
// input is not a float
}
Another option is to use a Scanner if you don't want to be handling exceptions:
Scanner scanner = new Scanner(dataEntry.getText());
if (scanner.hasNextFloat()) {
firstEntry = scanner.nextFloat();
} else {
// input is not a float
}
I would avoid of using catch-mechanism of exceptions to check if the value is a number because this is a very expensive procedure in java.
It would be better if you use FormattedTextFields: formattedtextfield
This needs some code but is a very elegant solution. You can also write your own formats with this concept.