I have a submit button in my program/JFrame it checks for validations and brings up error messages and then another form pops up and has all entered details:
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {
//VALIDATIONS-----------------------------------------------------------
if(txtName.getText().trim().equals(""))
{
JOptionPane.showMessageDialog(null, "Must have name");
jlblNameVer.setVisible(true);
}
else
{
jlblNameVer.setVisible(false);
}
//ID VERIFICATION
if (txtIdNumber.getText().trim().equals(""))
{
JOptionPane.showMessageDialog(null, "Photo Id must not be emplty");
}
//EMAIL VALIDATION
if(txtEmail==null ||txtEmail.getText().length() < 10|| txtEmail.getText()== null ||!(txtEmail.getText().trim().contains("#") && txtEmail.getText().trim().contains(".")))
{
JOptionPane.showMessageDialog(null, "Invalid Email");
}
//Phone Number Validation
if(txtPhoneNum.getText().length() < 10)
{
JOptionPane.showMessageDialog(null, "Must atleast 10 characters");
}
//COMBOBOX VALIDATIONS
if(cmbStayDuration.getSelectedIndex() == -1)
{
JOptionPane.showMessageDialog(null, "Please select stay duration");
}
//Photo ID
if(cmbPhotoId.getSelectedIndex() == -1)
{
JOptionPane.showMessageDialog(null, "Please select Photo ID type");
}
//Popup form
jfrmDetails nf1 = new jfrmDetails();
jfrmDetails.txtRoomTypef2.setText(this.cmbRoomType.getSelectedItem().toString());
jfrmDetails.txtRoomNumf2.setText(this.cmbRoomNumber.getSelectedItem().toString());
jfrmDetails.txtCheckIn.setText(this.ftxtCheckinDate.getText());
jfrmDetails.txtCheckOut.setText(this.txtCheckOut.getText());
jfrmDetails.txtName.setText(this.txtName.getText());
jfrmDetails.txtIdType.setText(this.cmbPhotoId.getSelectedItem().toString());
jfrmDetails.txtIdNum.setText(this.txtIdNumber.getText());
jfrmDetails.txtPhoneNum.setText(this.txtPhoneNum.getText());
jfrmDetails.txtEmail.setText(this.txtEmail.getText());
nf1.setVisible(true);
}
The problem is even when these validations are wrong the form will pop up anyway
If any of the validations are incorrect I don't want the popup form to show, what must I do?
You either need to restructure you if blocks into a if-else if-else block, so that last (else) condition would show the new view or use a boolean field which determines if the validation passed or not, for example...
boolean passed = true;
if (txtName.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Must have name");
jlblNameVer.setVisible(true);
passed = false;
} else {
jlblNameVer.setVisible(false);
}
//ID VERIFICATION
if (txtIdNumber.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Photo Id must not be emplty");
passed = false;
}
//EMAIL VALIDATION
if (txtEmail == null || txtEmail.getText().length() < 10 || txtEmail.getText() == null || !(txtEmail.getText().trim().contains("#") && txtEmail.getText().trim().contains("."))) {
JOptionPane.showMessageDialog(null, "Invalid Email");
passed = false;
}
//Phone Number Validation
if (txtPhoneNum.getText().length() < 10) {
JOptionPane.showMessageDialog(null, "Must atleast 10 characters");
passed = false;
}
//COMBOBOX VALIDATIONS
if (cmbStayDuration.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select stay duration");
passed = false;
}
//Photo ID
if (cmbPhotoId.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select Photo ID type");
passed = false;
}
if (passed) {
//Popup form
jfrmDetails nf1 = new jfrmDetails();
jfrmDetails.txtRoomTypef2.setText(this.cmbRoomType.getSelectedItem().toString());
jfrmDetails.txtRoomNumf2.setText(this.cmbRoomNumber.getSelectedItem().toString());
jfrmDetails.txtCheckIn.setText(this.ftxtCheckinDate.getText());
jfrmDetails.txtCheckOut.setText(this.txtCheckOut.getText());
jfrmDetails.txtName.setText(this.txtName.getText());
jfrmDetails.txtIdType.setText(this.cmbPhotoId.getSelectedItem().toString());
jfrmDetails.txtIdNum.setText(this.txtIdNumber.getText());
jfrmDetails.txtPhoneNum.setText(this.txtPhoneNum.getText());
jfrmDetails.txtEmail.setText(this.txtEmail.getText());
nf1.setVisible(true);
}
or
if (txtName.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Must have name");
jlblNameVer.setVisible(true);
} else {
jlblNameVer.setVisible(false);
//ID VERIFICATION
if (txtIdNumber.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Photo Id must not be emplty");
passed = false;
} else if (txtEmail == null || txtEmail.getText().length() < 10 || txtEmail.getText() == null || !(txtEmail.getText().trim().contains("#") && txtEmail.getText().trim().contains("."))) {
JOptionPane.showMessageDialog(null, "Invalid Email");
passed = false;
} else if (txtPhoneNum.getText().length() < 10) {
JOptionPane.showMessageDialog(null, "Must atleast 10 characters");
passed = false;
} else if (cmbStayDuration.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select stay duration");
passed = false;
} else if (cmbPhotoId.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select Photo ID type");
passed = false;
} else {
//Popup form
jfrmDetails nf1 = new jfrmDetails();
jfrmDetails.txtRoomTypef2.setText(this.cmbRoomType.getSelectedItem().toString());
jfrmDetails.txtRoomNumf2.setText(this.cmbRoomNumber.getSelectedItem().toString());
jfrmDetails.txtCheckIn.setText(this.ftxtCheckinDate.getText());
jfrmDetails.txtCheckOut.setText(this.txtCheckOut.getText());
jfrmDetails.txtName.setText(this.txtName.getText());
jfrmDetails.txtIdType.setText(this.cmbPhotoId.getSelectedItem().toString());
jfrmDetails.txtIdNum.setText(this.txtIdNumber.getText());
jfrmDetails.txtPhoneNum.setText(this.txtPhoneNum.getText());
jfrmDetails.txtEmail.setText(this.txtEmail.getText());
nf1.setVisible(true);
}
}
You should also have a look at The Use of Multiple JFrames, Good/Bad Practice? and maybe consider using a CardLayout instead, but this will depend on your underlying needs
You could also have a look at Validating Input, which would allow you to do post validation of your fields when the lose focus
Related
Unfortunately, I do not understand the problem with this part of my code.
I'm setting up a registration system.
It seems to be wrong when recording correct information.
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty() &&
!(name.length() < 4) && !(password.length()<5) && email.lastIndexOf(".") - email.indexOf("#") > 2 &&
email.contains(".") && email.lastIndexOf("#") < email.lastIndexOf(".")
&& email.contains("#") ) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Something is Wrong! ", Toast.LENGTH_LONG)
.show();
}
please, help me to edit this. thank you
Use this to validate emails:
public final static boolean isValidEmail(CharSequence target) {
return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches()); }
It is possible that your email validation is wrong here.
Your final code snippet:
if (!name.isEmpty() && !name.length() < 4) && (!password.isEmpty() &&!(password.length()<5)) && isValidEmail(emailId)) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Something is Wrong! ", Toast.LENGTH_LONG)
.show();
}
instead of messing up your validation do a neat check. Either use this email validation
public static boolean isValidEmaillId(String email){
return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
}
Or this one:
public static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
and then do your validation like this:
if (!name.isEmpty() && !name.length() < 4) && (!password.isEmpty() &&!(password.length()<5)) && isValidEmail(emailId)) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Something is Wrong! ", Toast.LENGTH_LONG)
.show();
}
I am trying to validate some edittext. I Made 7 edittexts. Phone number ,First name , Last name , Pickup Address, Postal Code, Pickup time, Number of products. As u can see i made 7 edittexts and I want to validate them so that when i press the button to go to next page it does all the database posting and getting on that button. I've already made a method (public void addInfo) and now i am adding the validations on the View.OnClick implemented methods. Here is my Code i wrote for validations.
public void onClick(View v) {
if (v == nextbuttonjava) {
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
}
if(firstnamejava.getText().toString().length() == 0)
{
firstnamejava.setError("Whats your first name?");
}
if(lastnamejava.getText().toString().length() == 0)
{
lastnamejava.setError("Whats your last name?");
}
if(pickupaddressjava.getText().toString().length() == 0)
{
pickupaddressjava.setError("Enter your address");
}
if(postalcodejava.getText().toString().length() < 6)
{
postalcodejava.setError("Invalid postal code");
}
if(pickuptimejava.getText().toString().length() == 0)
{
pickuptimejava.setError("Enter pickuptime");
}
if(numberstuffjava.getText().toString().length() == 0) {
numberstuffjava.setError("Enter number of clothes");
}
else
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
}
}
I Want that every If statement should be true to make the else work so the intent works and i go to the other activity. But its not the scene here. Only the phone number works good(If i enter the phone number below 10 digits it shows the error and it doesn't run else part). My main concern is that I Have 7 edittexts and Even if one If statement goes true then the else shouldn't be running and i shouldn't go to next intent with posting incomplete data on my database.I Want that even if any of the edittexts if statement goes wrong i should get an error (eg, numberstuffjava.setError("Input Something");.
How to resolve the issue?
Try something like this:
public void onClick(View v) {
if (v == nextbuttonjava) {
boolean error = false;
if(phnumberjava.getText().toString().length() < 10)
{
error = true;
phnumberjava.setError("Invalid Phone Number");
}
if(firstnamejava.getText().toString().isEmpty())
{
error = true;
firstnamejava.setError("Whats your first name?");
}
if(lastnamejava.getText().toString().isEmpty())
{
error = true;
lastnamejava.setError("Whats your last name?");
}
if(pickupaddressjava.getText().toString().isEmpty())
{
error = true;
pickupaddressjava.setError("Enter your address");
}
if(postalcodejava.getText().toString().length() < 6)
{
error = true;
postalcodejava.setError("Invalid postal code");
}
if(pickuptimejava.getText().toString().isEmpty())
{
error = true;
pickuptimejava.setError("Enter pickuptime");
}
if(numberstuffjava.getText().toString().isEmpty())
{
error = true;
numberstuffjava.setError("Enter number of clothes");
}
if(!error)
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
} else {
//manage error case here
}
}
}
another option could be this:
if (v == nextbuttonjava) {
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
}
else if(firstnamejava.getText().toString().isEmpty())
{
firstnamejava.setError("Whats your first name?");
}
else if(lastnamejava.getText().toString().isEmpty())
{
lastnamejava.setError("Whats your last name?");
}
else if(pickupaddressjava.getText().toString().isEmpty())
{
pickupaddressjava.setError("Enter your address");
}
else if(postalcodejava.getText().toString().length() < 6)
{
postalcodejava.setError("Invalid postal code");
}
else if(pickuptimejava.getText().toString().isEmpty())
{
pickuptimejava.setError("Enter pickuptime");
}
else if(numberstuffjava.getText().toString().isEmpty())
{
numberstuffjava.setError("Enter number of clothes");
}
else
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
else
{
//manage error case here
}
}
In this way you check any case with the else if. I prefer the first solution because it's more "flexible".
Hope this helps!
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
return "Error message";
}
else {
return null;
}
return like this in each and every if condition. If the return statement is null, then all if conditions are true. else show the error message returned
Among other things, you can try the following logic. Here, you can be assured that all the error messages will be shown:
if (v == nextbuttonjava) {
boolean validated = true;
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
validated = false;
}
if(firstnamejava.getText().toString().length() == 0)
{
firstnamejava.setError("Whats your first name?");
validated = false;
}
if(lastnamejava.getText().toString().length() == 0)
{
lastnamejava.setError("Whats your last name?");
validated = false;
}
if(pickupaddressjava.getText().toString().length() == 0)
{
pickupaddressjava.setError("Enter your address");
validated = false;
}
if(postalcodejava.getText().toString().length() < 6)
{
postalcodejava.setError("Invalid postal code");
validated = false;
}
if(pickuptimejava.getText().toString().length() == 0)
{
pickuptimejava.setError("Enter pickuptime");
validated = false;
}
if(numberstuffjava.getText().toString().length() == 0) {
numberstuffjava.setError("Enter number of clothes");
validated = false;
}
// fire in the hole !
if (validated)
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
}
The else condition it's only attached to the numberstuffjava if condition, in this scenario the else condition will be called always when this if condition is false.
Try changing the previous if conditions with else if.
You just create a method which return true only if all your needs are satisfied. if the method return true, then only go to next activity. I will give an example here.
public boolean isValid(){
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
return false;
}
if(firstnamejava.getText().toString().length() == 0)
{
firstnamejava.setError("Whats your first name?");
return false;
}
return true;
}
Then do things like below.
if(isValid()){
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
just add else if for checking all validation
if (v == nextbuttonjava) {
if (edittext1.getText().toString().length() < 5) {
edittext1.setError("error");
} else if (edittext2.getText().toString().length() == 0) {
edittext2.setError("error");
} else {
// your intent here
}
}
add else if for every of your edittext .
Try out below method to check an empty value of edittext.
public static boolean m_isError = false;
/**
* This is method to check edit text empty or not.
*
* #param p_editText
* - edittext
* #param p_nullMsg
* -display message if edittext null
*/
public static void validateForEmptyValue(EditText p_editText,
String p_nullMsg) {
if (p_editText != null && p_nullMsg != null) {
// use trim() while checking for blank values
if (TextUtils.isEmpty(p_editText.getText().toString().trim())) {
m_isError = true;
p_editText.setError(p_nullMsg);
}
}
}
Use the above method as below for each of your edittext:
CustomValidator.m_isError = false;
CustomValidator.validateForEmptyValue(metfirstname, "enter firstname", metfirstname);
CustomValidator.validateForEmptyValue(metlastname, "enter lastname", metlastname);
if (!CustomValidator.m_isError) {
//Define your logic once all the validations are done.
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
I am trying to output the information from the Salaried class in the EmployeesApplet class using the toString method in Salaried, however i keep receiving the error
EmployeesApplet.java:292: error: non-static method toString() cannot be referenced from a static context
ta.append(Salaried.toString());
^
How do i get around this error to display the information correctly?
here is the Salaried class
public class Salaried extends Employee
{
private double weekly_salary;
public Salaried(String first_name, String last_name, int e, double w ) // one constructor
{
super(first_name,last_name, e);
weekly_salary = w;
}
public String toString()
{
return super.toString() + " \nWeekly Salary" + weekly_salary ;
} // toString method
}
and here is the EmployeesApplet class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EmployeesApplet extends JApplet implements ActionListener
{
public JButton sd = new JButton ("Salaried");
public JButton hr = new JButton ("Hourly");
public JButton cm = new JButton ("Commissioned");
public JButton cl = new JButton ("Clear");
private final int FIELDS = 8,
FIELD_WIDTH = 20;
private String[] strings = new String[FIELDS];
private TextFieldWithLabel[] tf = new TextFieldWithLabel[FIELDS];
private JTextArea ta = new JTextArea(5,25);
String[] s = {"First Name", "Last Name", "Employee ID", "(a) Salaried: Weekly Salary", "(b1) Hourly 1: Rate Per Hour",
"(b2) Hourly 2: Hours Worked" , "(c1) Commissioned: Rate", "(c2) Commissioned: Gross Sales" };
public void init()
{
this.setSize(420, 310);
//----------------------
// Set up the Structure
//----------------------
Container c = getContentPane();
JPanel f = new JPanel(new FlowLayout());
JPanel b = new JPanel(new BorderLayout(2,0));
JPanel glb = new JPanel(new GridLayout(8,1,0,2));
JPanel gtf = new JPanel(new GridLayout(8,1,0,2));
JPanel flb = new JPanel(new FlowLayout());
// Add FlowLayout to the container
c.add(f);
// Add BorderLayout to the FlowLayout
f.add(b);
//---------------------------------------
//Add JPanels to the BorderLayout regions
//---------------------------------------
// Add JLables to GridLayout in West
b.add(glb, BorderLayout.WEST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
glb.add(tf[i].getLabel());
}
// Add JTextFeilds to GridLayout in East
b.add(gtf, BorderLayout.EAST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
tf[i].getTextField();
gtf.add(tf[i].getTextField());
}
// Add JButtons to FlowLayout in South
b.add(flb, BorderLayout.SOUTH);
flb.add(sd);
flb.add(hr);
flb.add(cm);
flb.add(cl);
sd.addActionListener(this);
hr.addActionListener(this);
cm.addActionListener(this);
cl.addActionListener(this);
// Add JTextArea and make it not editable
f.add(ta);
ta.setEditable(false);
}
//---------------------------------------
// Read all the JTextFields and
// save the contents in a parallel array
//---------------------------------------
private void readFields()
{
for (int i = 0; i < tf.length; i++) // or FIELDS
strings[i] = tf[i].getText();
}
private boolean fieldsExist(int i, int i2)
{
if(i == 0 && i2 == 3) // Checks Salaried worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty"); // Diplays error message in status area
tf[0].getTextField().requestFocus(); // Places focus in JTextField
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else if(tf[3].getText() == null || tf[3].getText().length() == 0)
{
showStatus("(a)Salried: Weekly Salary field is empty");
tf[3].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 0 && i2 == 2) // Checks Hourly worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 4 && i2 == 5) // Checks Hourly worker the second time
{
if(tf[4].getText() == null || tf[4].getText().length() == 0)
{
showStatus("(b1) Hourly 1: Rate Per Hour field is empty");
tf[5].getTextField().requestFocus();
return false;
}
else if(tf[5].getText() == null || tf[5].getText().length() == 0)
{
showStatus("(b2) Hourly 2: Hours Worked field is empty");
tf[5].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 0 && i2 == 2) // Checks Commissioned worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 6 && i2 == 7) // Checks Commissioned second time
{
if(tf[6].getText() == null || tf[6].getText().length() == 0)
{
showStatus("(c1)Commissioned: Rate field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[7].getText() == null || tf[7].getText().length() == 0)
{
showStatus("(c2)Commissioned: Ratefield is empty");
tf[1].getTextField().requestFocus();
return false;
}
else
return true;
}
return false;
}
private boolean fieldsEmpty(int i, int i2, String[] a)
{
if(i == 4 && i2 == 7) // checks salaried
{
for (int index = 4; index <= 7; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus( a[index] + " should be empty"); // Diplays error message in status area
tf[index].getTextField().requestFocus(); // Places focus in JTextField
return true;
}
else return false;
} // end for
} // end if
if (i == 3 && i2 == 3) // checks hourly first time
{
if(tf[3].getText().length() != 0)
{
showStatus(a[3] + " field should be empty");
tf[3].getTextField().requestFocus();
return true;
}
} // end if
if(i == 6 && i2 == 7) // checks hourly second time
{
for (int index = 6; index <= 7; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus(a[index] + " field should be empty");
tf[index].getTextField().requestFocus();
return true;
}
} // end for
} // end if
if(i == 3 && i2 == 5) // checks commissioned
{
for (int index = 3; index <= 5; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus(a[index] + " field should be empty");
tf[index].getTextField().requestFocus();
return true;
}
} // end for
} // end if
return false;
}
public void actionPerformed(ActionEvent e)
{
showStatus("");
if (e.getSource() == cl) // Executes clear button is clicked
{
for (int i = 0; i < FIELDS; i++)
{
tf[i].getTextField().setText("");
tf[0].getTextField().requestFocus();
}
} // End clear if
if (e.getSource() != cl)
{
if(e.getSource() == sd) // checks for salaried employee
{
showStatus("Salaried");
fieldsExist(0,3);
fieldsEmpty(4,7, s);
ta.append(Salaried.toString());
} // end salaried
if(e.getSource() == hr) // checks for hourly employee
{
showStatus("Hourly");
fieldsExist(0,2);
fieldsExist(4,5);
fieldsEmpty(3,3, s);
fieldsEmpty(6,7, s);
} // end hourly
if(e.getSource() == cm) // checks for commissioned employee
{
showStatus("Commissioned");
fieldsExist(0,2);
fieldsExist(6,7);
fieldsEmpty(3,5, s);
} // end commisssioned
} // end if
} // End of actionPerformed
}
As the error states, toString() is not static, you need to run it on an instance of Salaried. e.g.
Salaried s = new Salaried();
s.toString(); // should work...
Without relevant section from EmployeeApplet I cannot advise further, note ta.append(Salaried.toString()); in the error message you posted, does not appear to correspond to fragment of EmployeeApplet you gave...
This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
hello guys this is my first question
if no row selected i want to catch that and display a message..
private void table_Order_EKeyPressed(java.awt.event.KeyEvent evt) {
int row = table_Order_E.getSelectedRow();
if (evt.getKeyCode() == KeyEvent.VK_INSERT)
{
}
try{
if ( evt.getKeyCode()==KeyEvent.VK_DELETE && row<0 )
{
System.err.println("No Row has been selected..."+row);
}else if(evt.getKeyCode()==KeyEvent.VK_DELETE && row >-1)
{
model.removeRow(row);//remov with delete key.
}
}catch(ArrayIndexOutOfBoundsException e){
JOptionPane.showMessageDialog(null, e);
}
}
You have to add a if condition and throw an exception from your try block.
Please refer http://beginnersbook.com/2013/04/throw-in-java/ for further reference
here is the updating of my code also there was an exception outside the try i moved the declaration of row inside the try and the problem solved thank u.
private void table_Order_EKeyPressed(java.awt.event.KeyEvent evt) {
try{
int row = table_Order_E.getSelectedRow();//the exception may be here.
if (row >=0 && evt.getKeyCode() == KeyEvent.VK_INSERT) {
model.addRow(rowData);//add with insert key
}else if(row<0 && evt.getKeyCode() == KeyEvent.VK_INSERT ){
System.err.println("No Row insert..!");
}
if (evt.getKeyCode() == KeyEvent.VK_DELETE && row < 0) {
} else if (evt.getKeyCode() == KeyEvent.VK_DELETE && row > -1) {
model.removeRow(row);//remov with delete key.
}
}catch(ArrayIndexOutOfBoundsException e){
if (evt.getKeyCode() == KeyEvent.VK_DELETE){
JOptionPane.showMessageDialog(null, "Please Choose a Row To Delete..");
}
else if(evt.getKeyCode() == KeyEvent.VK_INSERT ){
JOptionPane.showMessageDialog(null, "Please Click Inside The Table To Add new Row..");
}
}
}
I have two EditText like editText1 and editText2.
I am taking input from EditText to name1 and name2.
Now I want to validate that the EditText are not empty before clicking on ok button.
For this I used:
if(editText1==NULL && editText2==NULL) {
textView.setText("please enter Names");
} else {
other code;
}
But its not validating, and with empty EditText it is showing result on clicking ok button.
I have also tried in this way:
if(name1==NULL && name2==NULL) {
textView.setText("please enter Names");
} else {
other code;
}
What to do?
Try this:
if(editText1.getText().toString().trim().equals("")
&& editText2.getText().toString().trim().equals(""))
{
textView.setText("Please enter Names");
}
else
{
// other code
}
Please use:
if(name1.compareTo("") == 0 || name2.compareTo("") == 0) {
// Your piece of code for example
Toast toast=Toast.makeText(getApplicationContext(), "ENTER NAMES", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
} else {
// Your code
}
This will work definitely for sure.
Try like this name1.equals("") in place of name1==NULL
if(name1.equals("") && name2.equals(""))
{
textView.setText("please enter Names");
}
else
{
other code;
}
if(name1.compareTo("") == 0 || name2.compareTo("") == 0)
{
// Your piece of code for example
}
you can use:
if(name.compareTo("") == 0 || name.compareTo(null) == 0) {}
This works very well for me, try this
if(editText1.getText().toString().length == 0 && editText2.getText().toString().length == 0)
{
textView.setText("Please enter names");
}
else
{
//some other actions to perform
}
if(editText1.getText().toString().length() > 0 && editText2.getText().toString().length() > 0)
{
textView.setText("Please enter Names");
}
else
{
// Other code
}