I tried
if(jRadioButton1.isSelected() ||(jRadioButton2.isSelected()) {
jGenderGroup.getSelection().getActionCommand();
} else {
jGndrErrorLabel.setText("Select gender.")
}
But controller doesn't stop after highlighted line it does go ahead to final line and throw NullPointerException
customers.setGender(jGenderGroup.getSelection().getActionCommand());
Where customers is POJO class.
How I can get rid of this?
try this :)
jRadioButton1.setActionCommand("Male");
jRadioButton2.setActionCommand("Female");
if(!jGenderGroup.isChecked()){
jLable1.setText("Please Select Gender");
}
if(jRadioButton1.isSelected())
{
//Male
}
else if(jRadioButton2.isSelected())
{
//Female
}
else
{
// no radio button has been selected
}
or alter your code like
if(jGenderGroup.getSelection() != null)
{
customer.setGender(jGenderGroup.getSelection().getActionCommand())
} else {
jGndrErrorLabel.setText("Select gender.")
}
I simply removed ButtonGroup jGenderGroup
and perform conditions for jRadioButton1 and jRadioButton2 at last instead of middle and as I had commented I can not set String gender = new String(); as
gender = jRadioButton1.getActionCommand();
Within conditional block because of POJO
So I just tricked that put it at the end like this :
String gender = new String();
if (jRadioButton1.isSelected()) {
gender = jRadioButton1.getActionCommand();
} else if (jRadioButton2.isSelected()) {
gender = jRadioButton2.getActionCommand();
} else {
jGndrErrorLabel.setText("Select gender.");
jGndrErrorLabel.setForeground(Color.red);
}
That's what I expected
Thanks for all of your time and efforts.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
i'm trying to disable some JButton with different account(something like permissions), here is my code to be more clear question...
try
{
stat = conn.prepareStatement(sql);
rs=stat.executeQuery();
while(rs.next())
{
System.out.println("found");
String _name= rs.getString("name");
String _pass = rs.getString("password");
String _stat = rs.getString("status");
if (_name == name && pass == _pass && _stat == "admin")
{
new SecondFrame().setVisible(true);//all buttons works as admin
}
else if(_name == name && pass == _pass && _stat == "moderator")
{
SecondFrame ob = new SecondFrame();
ob.admin_btn.setEnabled(false);//just user+moderator button works
}
else if(_name == name && pass == _pass && _stat == "user")
{
SecondFrame ob = new SecondFrame();
ob.admin_btn.setEnabled(false);
ob.moderator_btn.setEnabled(false);
// just user button works
}
}
}
catch (SQLException SQLe)
{
System.out.println("not executed"+SQLe);
}
... but i can't disable buttons like this(syntax is wrong), is there a way to make buttons disabled from this class?
thanks for help
1. String comparison error
Your main error is that you compare Strings with == in your code. In Java, this comparator will only work properly with basic types like long, double, boolean etc. therefore : use _stat.equals("moderator").
The reason why == won't work is that it compares the object's memory address instead of the inner values.
here's a code you can use :
try {
stat = conn.prepareStatement(sql);
rs=stat.executeQuery();
while(rs.next()) {
System.out.println("found");
String _name= rs.getString("name");
String _pass = rs.getString("password");
String _stat = rs.getString("status");
if (_name.equals(name) && pass.equals(_pass) && _stat.equals("admin")) {
new User().setVisible(true);//all buttons works as admin
} else if(_name.equals(name) && pass.equals(_pass) && _stat.equals("moderator")) {
SecondFrame ob = new SecondFrame();
ob.admin_btn.setEnabled(false);//just user+moderator button works
} else if(_name.equals(name) && pass.equals(_pass) && _stat.equals("user")) {
SecondFrame ob = new SecondFrame();
ob.admin_btn.setEnabled(false);
ob.moderator_btn.setEnabled(false);
// just user button works
}
}
} catch (SQLException SQLe) {
System.out.println("not executed"+SQLe);
}
2. Access related issue
After that, your code may still not work since you may have an access issue. Check if your SecondFrame class's button attributes are public. If they are not, you would better create a method that will set enabled inside that class for you with the user's access. Something like this :
public void setButtonAccess (String pAccess) {
user_button.setEnabled(false);
moderator_btn.setEnabled(false);
admin_btn.setEnabled(false);
if (pAccess.equals("user")) {
user_btn.setEnabled(true);
} else if (pAccess.equals("moderator")) {
user_btn.setEnabled(true);
moderator_btn.setEnabled(true);
} else if (pAccess.equals("admin")) {
user_button.setEnabled(true);
moderator_btn.setEnabled(true);
admin_btn.setEnabled(true);
}
}
Although the use of an enum would suit this situation pretty well... But for more information, I suggest the following readings :
Enum Types in Java
The switch statement
I am passing a String name to a method, if that name isn't in the array then it gets added.
I tried this first but got Concurrent Modification Exception
List<String> people = new ArrayList<>();
public void addName(String name) {
if (people.isEmpty()) {
people.add(name);
} else {
for (String s : people) {
if (s.equals(name)) {
System.out.println("dont add");
} else {
people.add(name);
}
}
}
}
After reading on forums I learned you have to use iterator to avoid this. I tried it and fixed the Concurrent Modification Exception, but the player gets added even though I stated them not to be added if they exist in the array, I do get this output "name exists" when I pass a name already existing in the list, but then it runs "name added" as well so dont understand why this is happening
if (people.isEmpty()) {
people.add(name);
} else {
String name2 = null;
for (Iterator<String> it = people.iterator(); it.hasNext(); ) {
String element = it.next();
if (element.equals(name)) {
String message = "name exists";
System.out.println(message);
name2 = null;
} else if (!element.equals(name)) {
System.out.println("Name added");
name2 = name;
}
}
if (name2 != null) {
people.add(name2);
}
}
You can do it simply by:
public void addName(String name) {
if (!people.contains(name)) {
people.add(name);
}
}
It sounds like you are trying to re-invent a set.
Set<String> names = new TreeSet<>(); // Or set of your choice
names.add("Joe"); // Set contents ["Joe"]
names.add("Bob"); // Set contents ["Joe", "Bob"];
names.add("Joe"); // Set contents ["Joe", "Bob"];
If you want to have the printlines
if (names.add(name) {
System.out.println("Added name " + name);
} else {
System.out.println("Already added " + name);
}
I reckon you need to break out of your loop once you find that the name already exists. Otherwise name2 might get set to null and then set to a non-null value again.
For example:
for (Iterator<String> it = people.iterator(); it.hasNext(); ) {
String element = it.next();
if (element.equals(name)) {
String message = "name exists";
System.out.println(message);
name2 = null;
break;
} else if(element.equals(name)==false) {
System.out.println("Name added");
name2 = name;
}
}
But do have a look at contains since this is a much much cleaner approach!
I am building java project in inventory management. following is the code i used for inserting color in database using equalsIgnorecase but it continuous showing Already exist. Please some one fix my code.
thanks
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
if(txtNewColor.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Fields should not be empty");
}
else
{
try {
String c = txtNewColor.getText();
ps =DbConnection.cn.prepareStatement("Select Color from color_details");
rs = ps.executeQuery();
int color = 0;
while (rs.next())
{
String cl= rs.getString("Color");
if(cl.equalsIgnoreCase(cl));
{
JOptionPane.showMessageDialog(null, "Aready Exist");
txtNewColor.setText("");
color=1;
}
}
if (color==0)
{
String strdata="Insert into color_details (Color)values(?)";
ps=DbConnection.cn.prepareStatement(strdata);
ps.setString(1, txtNewColor.getText());
ps.execute();
JOptionPane.showMessageDialog(null, "New Color Added Successfully");
cleartext();
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
refreshTable();
}
Try change if(cl.equalsIgnoreCase(cl)); to if(c.equalsIgnoreCase(cl))
Had not spotted the semi-colon at the end of your if statement
You are comparing the same String again. So It always results in a true, also the ; will skip even if they match. Remove it.
String c = txtNewColor.getText();
ps =DbConnection.cn.prepareStatement("Select Color from color_details");
rs = ps.executeQuery();
int color = 0;
while (rs.next())
{
String cl= rs.getString("Color");
if(cl.equalsIgnoreCase(c))
{
JOptionPane.showMessageDialog(null, "Aready Exist");
txtNewColor.setText("");
color=1;
}
}
You used same two strings to compare. so change c.equalsIgnoreCase(c1). Also make sure you have removed trailing spaces when getting input from text fields. it may makes your comparison fail.
String c = txtNewColor.getText().trim();
Remove the semi colon after if clause
if(cl.equalsIgnoreCase(cl)); ---> if(cl.equalsIgnoreCase(cl))
I managed to display 1 record of the asked category but what i need is for the program to display everything from that category. If it's too vague the code might help. Thanks in advance
public static void SearchCatRecord() throws Exception
{
LoadFile();
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------SEARCH CATEGORIZED ITEM--------");
System.out.println("\n\t\t\t*******************************");
System.out.print("\t\t\tEnter Category: ");
String searchnum = br.readLine();
boolean found = false;
for(int i=0;i<row;i++)
{
String record[] = list.get(i).split(",");
String num = record[1];
if(searchnum.equals(num))
{
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------RECORD FOUND----------");
System.out.println("\n\t\t\tProduct Number : "+record[0]);
System.out.println("\t\t\tCategory : "+record[1]);
System.out.println("\t\t\tProduct Name : "+record[2]);
System.out.println("\t\t\tPrice : "+record[3]);
System.out.println("\t\t\tQuantity : "+record[4]);
System.out.println("\n\t\t\t*******************************");
Thread.sleep(2000);
found = true;
System.out.println("\n\n\t\t\tSearch Completed");
exiting();
}
}
if(found == false)
{
System.out.println("\t\t\tNo Record Found");
System.out.println("\t\t\t*******************************");
exiting();
}
MainMenu();
}
The following code asks the user which category should the program display. then it displays the asked category but it only displays one record.
This is because you call exiting(); when you found the first record. You should remove it in your loop.
for example:
for(int i=0;i<row;i++)
{
String record[] = list.get(i).split(",");
String num = record[1];
if(searchnum.equals(num))
{
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------RECORD FOUND----------");
System.out.println("\n\t\t\tProduct Number : "+record[0]);
System.out.println("\t\t\tCategory : "+record[1]);
System.out.println("\t\t\tProduct Name : "+record[2]);
System.out.println("\t\t\tPrice : "+record[3]);
System.out.println("\t\t\tQuantity : "+record[4]);
System.out.println("\n\t\t\t*******************************");
Thread.sleep(2000);
}
}
System.out.println("\n\n\t\t\tSearch Completed");
if(found == false)
{
System.out.println("\t\t\tNo Record Found");
System.out.println("\t\t\t*******************************");
}
exiting();
If you want to find all the records then you should not breakout after finding one record that meets your criteria. I believe your method invocation exiting() is not needed in loop.
On a side note why are you setting found=true twice in the loop? Also what is the need of Thread.sleep(2000) in the code?
Is there a way to validate a number of JTextfields in java without the if else structure. I have a set of 13 fields, i want an error message when no entry is given for any of the 13 fields and to be able to set focus to that particular textbox. this is to prevent users from entering empty data into database. could someone show me how this can be achieved without the if else structure like below.
if (firstName.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (lastName.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (emailAddress.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (phone.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else {
//code to enter values into MySql database
the above code come under the actionperformed method a of a submit registration button. despite setting fields in MySQL as NOT NULL, empty string were being accepted from java GUI. why is this? i was hoping perhaps an empty string exception could be thrown from which i could customise a validation message but was unable to do so as empty field were being accepted.
Thanks
Just for fun a little finger twitching demonstrating a re-usable validation setup which does use features available in core Swing.
The collaborators:
InputVerifier which contains the validation logic. Here it's simply checking for empty text in the field in verify. Note that
verify must not have side-effects
shouldYieldFocus is overridden to not restrict focus traversal
it's the same instance for all text fields
a commit action that checks the validity of all children of its parent by explicitly invoking the inputVerifier (if any) and simply does nothing if any is invalid
a mechanism for a very simple though generally available error message taking the label of the input field
Some code snippets
// a reusable, shareable input verifier
InputVerifier iv = new InputVerifier() {
#Override
public boolean verify(JComponent input) {
if (!(input instanceof JTextField)) return true;
return isValidText((JTextField) input);
}
protected boolean isValidText(JTextField field) {
return field.getText() != null &&
!field.getText().trim().isEmpty();
}
/**
* Implemented to unconditionally return true: focus traversal
* should never be restricted.
*/
#Override
public boolean shouldYieldFocus(JComponent input) {
return true;
}
};
// using MigLayout for lazyness ;-)
final JComponent form = new JPanel(new MigLayout("wrap 2", "[align right][]"));
for (int i = 0; i < 5; i++) {
// instantiate the input fields with inputVerifier
JTextField field = new JTextField(20);
field.setInputVerifier(iv);
// set label per field
JLabel label = new JLabel("input " + i);
label.setLabelFor(field);
form.add(label);
form.add(field);
}
Action validateForm = new AbstractAction("Commit") {
#Override
public void actionPerformed(ActionEvent e) {
Component source = (Component) e.getSource();
if (!validateInputs(source.getParent())) {
// some input invalid, do nothing
return;
}
System.out.println("all valid - do stuff");
}
protected boolean validateInputs(Container form) {
for (int i = 0; i < form.getComponentCount(); i++) {
JComponent child = (JComponent) form.getComponent(i);
if (!isValid(child)) {
String text = getLabelText(child);
JOptionPane.showMessageDialog(form, "error at" + text);
child.requestFocusInWindow();
return false;
}
}
return true;
}
/**
* Returns the text of the label which is associated with
* child.
*/
protected String getLabelText(JComponent child) {
JLabel labelFor = (JLabel) child.getClientProperty("labeledBy");
return labelFor != null ? labelFor.getText() : "";
}
private boolean isValid(JComponent child) {
if (child.getInputVerifier() != null) {
return child.getInputVerifier().verify(child);
}
return true;
}
};
// just for fun: MigLayout handles sequence of buttons
// automagically as per OS guidelines
form.add(new JButton("Cancel"), "tag cancel, span, split 2");
form.add(new JButton(validateForm), "tag ok");
There are multiple ways to do this, one is
JTextField[] txtFieldA = new JTextField[13] ;
txtFieldFirstName.setName("First Name") ; //add name for all text fields
txtFieldA[0] = txtFieldFirstName ;
txtFieldA[1] = txtFieldLastName ;
....
// in action event
for(JTextField txtField : txtFieldA) {
if(txtField.getText().equals("") ) {
JOptionPane.showMessageDialog(null, txtField.getName() +" is empty!");
//break it to avoid multiple popups
break;
}
}
Also please take a look at JGoodies Validation that framework helps you validate user input in Swing applications and assists you in reporting validation errors and warnings.
Take an array of these three JTextField, I am giving an overview
JTextField[] fields = new JTextField[13]
field[0] = firstname;
field[1] = lastname; //then add remaining textfields
for(int i = 0; i < fields.size(); ++i) {
if(fields[i].getText().isEmpty())
JOptionPane.showMessageDialog(null, "No data entered");
}
Correct me if i'm wrong, I am not familiar with Swing or awt.HTH :)
Here is one way to do it:
public static boolean areAllNotEmpty(String... texts)
{
for(String s : texts) if(s == null || "".equals(s)) return false;
return true;
}
// ...
if(areAllNotEmpty(firstName, lastName, emailAddress, phone))
{
JOptionPane.showMessageDialog(null, "No data entered");
}