Error in Importing Boolean variable - java

I have two classes , one called AdminMenu class where variable VoteCycle is a boolean variable that enables a voter to vote provided that the VoteCycle is enabled and another class called LogInMenu where I would like to utilize it.
I'm doing this for my school project.
The problem I have is that even if I select enable which is meant to change the boolean value to true , I'm still getting the false output.. If you don't understand what I mean, my code below should explain it.
Its very basic programming.
The Class
public class AdminMenu extends javax.swing.JFrame {
public boolean VoteCycle;
The method
private void VoteComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
if(vCycle.getSelectedItem().toString().equalsIgnoreCase("True"))
{
VoteCycle=true;
}
else if(vCycle.getSelectedItem().toString().equalsIgnoreCase("False"))
{
VoteCycle=false;
}
}
This is the class where I would like to use the variable to allow users to log in.
The class is called LogInMenu().
At the start of the class I created an object of the class where the variable was defined in using
AdminMenu AdminMenu=new AdminMenu();
DataValidation validate=new DataValidation();
ConnectDB db=new ConnectDB();
I will just post the relevant code for this class:
private void EnterBtnActionPerformed(java.awt.event.ActionEvent evt) {
if(AdminMenu.VoteCycle)
{
String Voter=voter.getText();
boolean detail = false;
if (validate.Verify(Voter))// Validates Data
{
try
{
detail = db.VoterLogIn(Voter);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
if (detail)
{
new VoterMenu().setVisible(true);
this.dispose();
}
else
{
JOptionPane.showMessageDialog(null, "The Username or Password entered is incorrect");// error message
}
}
}
else
{
JOptionPane.showMessageDialog(null, "Voting is currently disabled", "Error", JOptionPane.ERROR_MESSAGE);
}
Even after selecting the combo box option to enabled, I return to the LogInMenu class
and if i attempt to login I receive the "Voting is currently disabled" error.
I would really appreciate any help offered , Thank you!
P.S : I'm unsure how to use a toggle button and allow its state to be kept when logging into the administrators menu or just how to use the toggle button at all.
So instead i'm using a combox box to set my variables values.

The problem I have is that even if I select enable which is meant to
change the boolean value to true , I'm still getting the false
output..
Because, the elements of your JComboBox vCycle are { "Disabled", "Enabled", " " } whereas, you are checking the selectedItem for true and false. You should compare the selected value of vCycle for Diabled or Enabled instead of true and false.
if(vCycle.getSelectedItem().toString().equalsIgnoreCase("Disabled"))
{
VoteCycle=true;
}
else if(vCycle.getSelectedItem().toString().equalsIgnoreCase("Enabled"))
{
VoteCycle=false;
}
}

Apart from checking for the wrong text value of True and False instead of Enabled and Disabled, your code doesn't handle the case where it's neither.
Change your code to the single line:
VoteCycle = vCycle.getSelectedItem().toString().equalsIgnoreCase("Enabled");
Not only is it less code, and more readable, it caters (one way or another) for the neither case.

Related

How can this java code display an output in BlueJ?

The code below is for a graphical user interface that has a loginframe that will enable the user to input their credentials. However, when I run the code it does not show an output. Can anyone help?
public void addComponentsToContainer() {
container.add(userLabel);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(showPassword);
container.add(loginButton);
container.add(resetButton);
}
public void addActionEvent() {
loginButton.addActionListener(this);
resetButton.addActionListener(this);
showPassword.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
//Coding Part of LOGIN button
if (e.getSource() == loginButton) {
String userText;
String pwdText;
userText = userTextField.getText();
pwdText = passwordField.getText();
if (userText.equalsIgnoreCase("admin") && pwdText.equalsIgnoreCase("12345")) {
JOptionPane.showMessageDialog( null, "Login Successful" );
Home obj= new Home();
obj.setVisible(true);
// setVisible(false);
} else {
JOptionPane.showMessageDialog ( null, "Invalid Username or Password");
}
}
//Coding Part of RESET button
if (e.getSource() == resetButton) {
userTextField.setText("");
passwordField.setText("");
}
//Coding Part of showPassword JCheckBox
if (e.getSource() == showPassword) {
if (showPassword.isSelected()) {
passwordField.setEchoChar((char) 0);
} else {
passwordField.setEchoChar('*');
}
}
}
}
You're not really showing enough information in this particular case which is why your are asked in comments to supply a Minimal Reproducible Example. Never the less, I'm going to go with the fact that you are utilizing a JPasswordField component.
To start with, for security reasons the JPasswordField#getText() method has been Deprecated as of Java 2 platform v1.2 and replaced with the JPasswordField#getPassword() method which returns a char[] Array of the password entered. Although you may still be able to compile with the getText() method for this component on the Java platform you're working with, you may be experiencing issues with it when actually running the code.
Try using the JPasswordField#getPassword() method instead and see if that makes a difference:
String userText = userTextField.getText();
String pwdText = String.valueOf(passwordField.getPassword());
if (userText.equalsIgnoreCase("admin") && pwdText.equalsIgnoreCase("12345")) {
and it should fly...maybe...who knows without a Minimal Reproducible Example. Are you using a JPasswordField or are you using a JTextField with a DocumentFilter to mask the entered text?
Maybe your code is working and you just can't see the Message Box because you use null as the parent for the JOptionPane:
JOptionPane.showMessageDialog( null, "Login Successful" );
and the message box dialog window is sitting behind your application window. This is rather typical if the application window has the setAlwaysOnTop() property set to boolean true. This can give the impression that the application is hanging. Give the dialog a parent...perhaps try loginButton instead of null.
On a side note:
Consider hashing passwords then compare a hash with a hash. You really shouldn't hard-code or store a password as plain-text.

How to disable jTextfield again when the other jTextfield is empty in java

Heya guys! Nolankr here.
I've got this code that enables my password jField when I place something inside the username jField but when I delete my inputs from the username jField my password jField stays enabled. I wanted it to go back to being disabled though. I'm still a starter so I'm so sorry.
private void usernameKeyTyped(java.awt.event.KeyEvent evt) {
String usern = username.getText();
if(usern != null){
password.setEnabled(true);
}else{
password.setEnabled(false);
}
}
I tried coding an infinite loop to it but it just made my .jar file to stop responding / won't close, so I had to close netbeans itself and restart it . xD
username and password are both jTextfields by the way and password is disabled by default
basically,
if username != null then enable password but if username = null again then disable password again
What you probably want is a document listener that will allow you to detect when the username field is changed and take appropriate action.
I'm writing this answer with the mobile app so it's hard to provide a code sample right now.
Basically you would set up the listener on username to check if username is null or empty and enable/disable the password field based on the result of that check.
EDIT:
I'm back at my computer now, and am able to provide a code sample. See below:
userNameTextBox.getDocument().addDocumentListener(new DocumentListener(){
#Override
public void insertUpdate(DocumentEvent e) {
handleTextChange();
}
#Override
public void removeUpdate(DocumentEvent e) {
handleTextChange();
}
#Override
public void changedUpdate(DocumentEvent e) {
//Do nothing here
}
private void handleTextChange(){
if(userNameTextBox.getText() == null ||
userNameTextBox.getText().trim().length() == 0){
passwordBox.setEnabled(false);
}else{
passwordBox.setEnabled(true);
}
}
});
Note that the changedUpdate method does nothing because it is not fired when the document text changes, it is fired when attributes change. See the javadoc for complete details.

How to enable / disable action in Netbeans Platform

I have spent almost three days trying to do a simple enable / disable of Actions in the netbeans plaform, something that I though was going to be simple, and should be a common feature is more complex than I thought.
At the begging I tried to see if there was an setEnable() method on the default actions generated and to my surprise there is not. Then I started looking into that and I found that most common method to do it was setting a conditionally enabled action (which depends on a Cookie class), So I figured out how to add a fake class to the Lookup so it gets enabled and disabled, I did it the following way. To test it out I added the following code to another action which should enable or disable the second one.
private final PlottingStarted plottingStarted = new PlottingStarted();
#Override
public void actionPerformed(ActionEvent e) {
// TODO implement action body
if (Lookup.getDefault().lookup(PlottingStarted.class) == null) {
ic.add(plottingStarted);
}else{
ic.remove(plottingStarted);
}
So PlottingStarted is a fake object I created which only purpose is being in the lookup to disable or enable the action.
For some reason it did not do anything at all an the Action was always disabled. I tried many things and finally I gave up.
Then I tried a different approach and was using AbstractActions which do have the setEnabled() ability.
To retrieve the action I based myself on one the Geertjan blogs and I created the following method
public Action findAction(String actionName) {
FileObject myActionsFolder = FileUtil.getConfigFile("Actions/RealTimeViewer");
if (myActionsFolder != null){
FileObject[] myActionsFolderKids = myActionsFolder.getChildren();
for (FileObject fileObject : myActionsFolderKids) {
//Probably want to make this more robust,
//but the point is that here we find a particular Action:
if (fileObject.getName().contains(actionName)) {
try {
DataObject dob = DataObject.find(fileObject);
InstanceCookie ic = dob.getLookup().lookup(InstanceCookie.class);
if (ic != null) {
Object instance = ic.instanceCreate();
if (instance instanceof Action) {
Action a = (Action) instance;
return a;
}
}
} catch (Exception e) {
ErrorManager.getDefault().notify(ErrorManager.WARNING, e);
return null;
}
}
}
}
return null;
}
This method worked perfectly and I was able to retrieve the action and call its setEnabled() method. Unfortunately no matter why I did the Action was always enabled.
Reading some literature I found that I should add the following to the registration of the action "lazy = false" and finally I was able to enable and disable the Action... But off course the default registration is lost and I have no Icons and Names.
Now I decided to post again because I cannot believe that it need to be that complex, there must be a way to do it easier. The only thing I need is to have a PLAY / STOP functionality, when PLAY is enabled STOP is disabled and vice-versa.
I have not done this myself but it seems to be covered in Chapter 5.1.2.1 "Complex Enablement" of the book "Netbeans Platform for Beginners". https://leanpub.com/nbp4beginners
The book is not free but the corresponding code sample is available on
github. https://github.com/walternyland/nbp4beginners/tree/master/chapters/ch05/5.1.2.1 He extends AbstractAction overrides the resultChanged method and uses super.setEnabled().
#ActionID(id = "org.carsales.evaluator.EvaluateCarAction1", category = "Car")
#ActionRegistration(displayName = "not-used", lazy = false)
public class EvaluateCarAction extends AbstractAction
implements ContextAwareAction, LookupListener {
// ...
#Override
public void resultChanged(LookupEvent le) {
//Optionally, check if the property is set to the value you're interested in
//prior to enabling the Action.
super.setEnabled(result.allInstances().size() > 0);
}
Thanks to everybody for your responses. I finally got it to work by extending AbstractAction, it seems that even if you register "lazy = false" some of the registration is still being done by the platform and you just need some minor tweaking in the Action constructor. The final result was
#ActionID(
category = "RealTimeViewer",
id = "main.java.com.graph.actions.StopPlotting"
)
#ActionRegistration(
//iconBase = "main/java/com/graph/images/stop-plotting-24x24.png",
displayName = "#CTL_StopPlotting",
lazy = false
)
#ActionReference(path = "Toolbars/RealTimeViewer", position = 600)
#Messages("CTL_StopPlotting=Stop Plotting")
public final class StopPlotting extends AbstractAction{
private static final String ICON = "main/java/com/dacsys/cna/core/graph/images/stop-plotting-24x24.png";
public StopPlotting() {
putValue(SMALL_ICON, ImageUtilities.loadImageIcon(ICON, false));
putValue(NAME, Bundle.CTL_StopPlotting());
this.setEnabled(false);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO implement action body
Action a = new ActionsHelper().findAction("StartPlotting");
if (a != null){
if (a != null){
if (a.isEnabled()){
a.setEnabled(false);
this.setEnabled(true);
}else{
a.setEnabled(true);
this.setEnabled(false);
}
}
}
}
}

CheckboxField gives StackOverflow Error in Blackberry java application

I am creating 2-3 checkbox field in my screen and adding those in a vertical field manager. Idea here is to disable other check box on click of another checkbox. but it is giving me stackoverflow error. I am posting my code here...
final CheckboxField[] checkBoxField = new CheckboxField[2];
checkBoxField[0] = cashCardCheckboxField;
checkBoxField[1] = creditDebitCardCheckboxField;
checkBoxField[0].setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if(context != FieldChangeListener.PROGRAMMATIC){ //It means manually clicked by User
if(checkBoxField[0].getChecked()){
checkBoxField[0].setChecked(false);
}else{
checkBoxField[0].setChecked(true);
//Please wait Screen starts
// call here a user defined function to populate the drop down list
//Please wait Screen ends
}
}else{
checkBoxField[0].setChecked(false);
}
}
});
checkBoxField[1].setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if(context != FieldChangeListener.PROGRAMMATIC){ //It means manually clicked by User
if(checkBoxField[1].getChecked()){
checkBoxField[1].setChecked(false);
}else{
checkBoxField[1].setChecked(true);
//Please wait Screen starts
// call here a user defined function to populate the drop down list
//Please wait Screen ends
}
}else{
checkBoxField[1].setChecked(false);
}
}
});
Thanks and Regards.
Solution
Try using this code. It allows you to create any number of checkboxes. When one is checked, the listener will uncheck all the other ones.
public class CheckBoxScreen extends MainScreen {
private CheckboxField checkBoxField[];
public CheckBoxScreen() {
super(MainScreen.VERTICAL_SCROLL | MainScreen.VERTICAL_SCROLLBAR);
checkBoxField = new CheckboxField[3];
checkBoxField[0] = new CheckboxField("one", true); // checked by default
checkBoxField[1] = new CheckboxField("two", false);
checkBoxField[2] = new CheckboxField("three", false);
FieldChangeListener listener = new CheckboxListener();
for (int i = 0; i < checkBoxField.length; i++) {
checkBoxField[i].setChangeListener(listener);
add(checkBoxField[i]);
}
}
private class CheckboxListener implements FieldChangeListener {
public void fieldChanged(Field field, int context) {
if (context != FieldChangeListener.PROGRAMMATIC) {
// user modified this field
CheckboxField checkbox = (CheckboxField)field;
if (checkbox.getChecked()) {
// uncheck the other checkboxes
for (int i = 0; i < checkBoxField.length; i++) {
if (checkBoxField[i] != checkbox && checkBoxField[i].getChecked()) {
checkBoxField[i].setChecked(false);
}
}
}
} else {
// nothing more to do here ... this time, fieldChanged() is being
// called as a result of calling setChecked() in the code.
}
}
}
}
Why Your Code Created a Stack Overflow
The fieldChanged() method gets called whenever a field has its properties modified. For a CheckboxField, that happens when the field is checked or unchecked. This can happen either because the user checks/unchecks the field, or because your code calls setChecked(boolean). This line:
if(context != FieldChangeListener.PROGRAMMATIC){ //It means manually clicked by User
is what allows the code inside fieldChanged() to determine if this call is occurring because the user changed the field, or because setChecked() was called by your code. Unfortunately, you have placed calls to setChecked() in all branches of the if statement, which causes setChecked() to be called both for user events, and when your code changes the fields.
In this code:
checkBoxField[0].setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if(context != FieldChangeListener.PROGRAMMATIC){ //It means manually clicked by User
if(checkBoxField[0].getChecked()){
checkBoxField[0].setChecked(false);
}else{
checkBoxField[0].setChecked(true);
//Please wait Screen starts
// call here a user defined function to populate the drop down list
//Please wait Screen ends
}
}else{
checkBoxField[0].setChecked(false);
}
}
});
it is the last line (checkBoxField[0].setChecked(false);) that is causing problems. That else branch is reached after calling setChecked() in the "manually clicked" branch of the if statement. Once you call setChecked(false) again, you have modified the field programmatically. This will cause fieldChanged() to be called back again. And again. And again. This loop will never stop, until the program stack is full, and your app crashes.
So, if you see my code, you notice that I am not calling setChecked() in the programmatic branch of the if statement. Another problem in your code is that you don't have the correct logic to uncheck checkbox 1 when checkbox 0 is checked. But, that's only a functional bug. The recursive call to fieldChanged() is what caused the stack overflow.
Hope that helps.

JoptionPane Validation

I have a Swing GUI where I am restricting the user registration so that the username and the password cannot be the same. I am using JoptionPane for the task with the following code:
public void actionPerformed(ActionEvent e) {
String username = tuser.getText();
String password1 = pass1.getText();
String password2 = pass2.getText();
String workclass = wclass.getText();
Connection conn = null;
try {
if(username.equalsIgnoreCase(password1)) {
JOptionPane.showMessageDialog(null,
"Username and Password Cannot be the same. Click OK to Continue",
"Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
...
The problem is that I had to use System.exit(0); without it, the next code was getting executed. Even after the JOptionPane poped up, the registration was succeeding. I do not need the system to exit, but I need the user to be kept on the registration page after the validation. What is the best way to do this? Is there other convenient ways of doing this rather than using the JOptionPane?
Replace
System.exit(0);
with
return;
if you do not want the rest of the method to be performed
You need to place your code within endless loop, and break it upon successful result. Something like:
while(true)
{
// get input from user
if(vlaidInput) break;
}
place that next code into else part may be it works
if(username.equalsIgnoreCase(password1))
{
JOptionPane.showMessageDialog(null, "Username and Password Cannot be the same. Click OK to Continue","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
//place that next code
// username and password not equals, then it will execute the code
}
First of all, it is best if the UI and business logic (in this case, validation) are separated. Have them separate sort of suggest a better way of handling interaction on its own. Thus, it makes sense to create a separate class UserValidation with method boolean isValid(). Something like this:
public class UserValidation {
private final String name;
private final String passwd;
private final String passwdRpt;
public UserValidation(final String name, final String passwd, final String passwdRpt) {
this.name = name;
this.passwd = passwd;
this.passwdRpt = passwdRpt;
}
public boolean isValid() {
// do your validation logic and return true if successful, or false otherwise
}
}
Then the action code would look like this:
public void actionPerformed(ActionEvent e) {
if (new UserValidation(tuser.getText(), pass1.getText(), pass2.getText()).isValid()) {
// do everything needed is validation passes, which should include closing of the frame of dialog used for entering credentials.
}
// else update the UI with appropriate error message -- the dialog would not close by itself and would keep prompting user for a valid entry
}
The suggested approach gives you a way to easily unit test the validation logic and use it in different situations. Please also note that if the logic in method isValid() is heavy than it should be executed by a SwingWorker. The invocation of SwingWorker is the responsibility of the action (i.e. UI) logic.

Categories

Resources