I have multiple JTextFields and JComboBox in my JFrame. So whenever I click the _Add_ button it will check if the four (4) text fields in Current Medication Panel is Empty. If it is not then Execute, but it also depends if the Personal info Panel text fields are filled.
But I have a problem when I use the if and else statement, if I use the if and else:
if(condition if the first textfield is empty) {
// execute something like the textfield turn to red
} else if(condition if the second textfield is empty) {
// execute something like the textfield turn to red
} else if(condition if the third textfield is empty) {
// execute something like the textfield turn to red
} else{
// execute save information of the patient
}
In this situation if the 1st text field is empty then it will turn to red but if both 1st and 2nd text field is empty only the 1st text field turn to red.
I also tried the if, and if and if but were should put the else whenever there is no empty or invalid input where it will execute and save the patient info like this:
if(condition if the first textfield is empty) {
// execute something like the textfield turn to red
}
if(condition if the second textfield is empty) {
// execute something like the textfield turn to red
}
if(condition if the third textfield is empty) {
// execute something like the textfield turn to red
}
if(condition if the fourth textfield is empty) {
// execute something like the textfield turn to red
} else
If I use this only the last if statement only works for the else statement.
So if the last statement is true then execute, but not then else statement execute which is patient save info.
Is there any thing I can do about this? or is there any tutorial for me to learn more about Java and about if and else?
In the Add button action listener's actionPerformed method, you can try this:
public void actionPerformed(ActionEvent e) {
if (! textFieldsValid()) {
// one or more of the text fields are empty
// may be display a message in a JOptionPane
System.out.println("The text fields are not filled with data, etc...");
return;
}
// else, text fields have valid data, so do whatever processing it further...
}
/*
* This method checks if the text fields are empty and sets their borders as red. Returns
* a boolean false in case any of the text fields are empty, else true.
*/
private boolean textFieldsValid() {
boolean validTextFields = true;
if (textField1.getText().isEmpty()) {
validTextFields = false;
textField1.setBorder(new LineBorder(Color.RED));
}
if (textField2.getText().isEmpty()) {
validTextFields = false;
// textField2.setBorder(...)
}
// ... same with textField3 and textField4
return validTextFields;
}
but were should put the else
It is not mandatory to follow if with else. The purpose of specifying else is to allow your code execution flow to go through all other case when if was not satisfied (true).
if i use this only the last if statement only works for the else
statement
Because, if might have satisfied, so it executes else case. I would suggest to include return in each if case. So that, if any of the if case was satisfied. Then, it won't execute further code.
This should not be news to you: you are doing it wrong.
There are several ways to implement your desired solution,
here is one of them:
boolean performSave = true;
if (field1 is empty)
{
do some stuff.
performSave = false;
}
if (field2 is empty)
{
do some stuff.
performSave = false;
}
... repeat for any number of fields.
if (performSave) // no fields are empty.
{
save stuff.
}
Related
It's a prototype for a virtual therapist, mainly for Java practice purposes. I've been trying to clear this JTextArea for 2 days now.
I've cleaned and rebuilt which got me through a few other hurdles, I'm at a loss for what to try. setEnabled() is coded out because I was just trying it on and off with different methods. Everything but the clear button works fine. I get a response in the text area after pressing enter with JTextField input. But it just won't clear.
public void actionPerformed(ActionEvent event)
{
String inp = event.toString(); //this is input in a JTextField
if(inp.contains("sad") || inp.contains("lonely"))
{
txtArea.setText(response1);
}else if(inp.contains(""))
{
txtArea.setText(response2);
}
else if(event.getSource() == clear) //clear is a button
{
//clear.setEnabled(true);
txtArea.setText(""); //I've tried selectAll(), replaceSelection()
}
}
From what I can see in your code this might help with the clear problem. In your code the if branch for the clear can never be reached due to the else after an condition(contains an emty string) that is always true. I moved it to the front - so it is reachable.
I can't say for sure from your posted code, but the event.toString() looks also suspicious as well as the last(in the changed code below) condition, that is always true.
//this looks odd/suspicious to me too!
String inp = event.toString(); //???!!! this is input in a JTextField
/* rather something like
* if(event.getSource() instanceof JTextField){
* inp = ((JTextField)event.getSource()).getText();
* }
*/
if(event.getSource() == clear) { //clear is a button
//clear.setEnabled(true);
txtArea.setText(""); //I've tried selectAll(), replaceSelection()
} else if(inp.contains("sad") || inp.contains("lonely")) {
txtArea.setText(response1);
} else if(inp.contains("")) { //??? always true!! rather: inp.equals("") or inp.isEmpty() ...
txtArea.setText(response2);
}
Im having trouble disabling the Buttons for a particular question in my mQuestionsBank array. I created a mQuestionsAnswered boolean array with the size of the mQuestionsBank array to keep track of the questions that have been answered. Now, when the user interacts with either the "True" or "False" button, mQuestionsAnswered[mCurrentIndex] gets set to true, therefore disabling both of the buttons whether if they are right or wrong. Heres my code
Method to Enable Buttons image
Method to Check Answer image
True and False Button onClickListeners image
This is the code from your first picture:
private void buttonEnabler(){
if (...) {
...
} else
mTrueButton.setEnabled(true);
mFalseButton.setEnabled(true);
}
You're missing brackets on the else case. That means that this code "really" looks like this:
private void buttonEnabler(){
if (...) {
...
} else
mTrueButton.setEnabled(true);
}
mFalseButton.setEnabled(true);
}
In other words, mFalseButton will always be enabled, even when you don't want it to be. To fix it, add the brackets surrounding the else lines:
private void buttonEnabler(){
if (...) {
...
} else {
mTrueButton.setEnabled(true);
mFalseButton.setEnabled(true);
}
}
In your method buttonEnable, there's the if else error
Use else with {} brackets always, unless the statements to be executed is just one as illustrated below...
if (true)
say 'hello
else
be quiet
Or
if(true) {
say 'hello'
say 'how may I help you're
} else {
say statement 3
say statement 4
}
I am trying to program a GUI that uploads a file with a song data base and allows a user to add, edit, or remove songs from this database. Song names appear in a combo box and when a song is selected, the pertinent information appears in un-editable text fields. The interface has buttons for add, edit, delete, accept, cancel, and exit. When either edit or add are selected, text fields become editable and the accept and cancel buttons are enabled. This functionality works okay, but the accept and cancel buttons do not work. When accept is chosen, a song is added, or current song is edited, and added to the combo box and accept and cancel are disabled while the other buttons become enabled and text fields become un-editable. Cancel should perform much the same way, but instead of adding or editing a song, the interface just reverts back to its original state. Below is the code for the actionPerformed class:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
int index = songBox.getSelectedIndex();
Song selection = songList.get(index);
Song newSong = new Song();
if (source == songBox) {
itemCodeField.setText(selection.getSongCode());
descriptionField.setText(selection.getSongName());
artistField.setText(selection.getSongArtist());
albumField.setText(selection.getSongAlbum());
priceField.setText(selection.getSongPrice());
}
if (source == addButton) {
//Enable and disable appropriate buttons
addButton.setEnabled(false);
editButton.setEnabled(false);
deleteButton.setEnabled(false);
acceptButton.setEnabled(true);
cancelButton.setEnabled(true);
exitButton.setEnabled(false);
//Clear text fields and make editable
itemCodeField.setText("");
itemCodeField.setEditable(true);
descriptionField.setText("");
descriptionField.setEditable(true);
artistField.setText("");
artistField.setEditable(true);
albumField.setText("");
albumField.setEditable(true);
priceField.setText("");
priceField.setEditable(true);
//Set song values
newSong.setSongCode(itemCodeField.getText());
newSong.setSongName(descriptionField.getText());
newSong.setSongArtist(artistField.getText());
newSong.setSongAlbum(albumField.getText());
newSong.setSongPrice(priceField.getText());
}
if (source == editButton) {
//Enable and disable appropriate buttons
addButton.setEnabled(false);
editButton.setEnabled(false);
deleteButton.setEnabled(false);
acceptButton.setEnabled(true);
cancelButton.setEnabled(true);
exitButton.setEnabled(false);
//Make text fields editable
descriptionField.setEditable(true);
artistField.setEditable(true);
albumField.setEditable(true);
priceField.setEditable(true);
}
if (source == deleteButton) {
songBox.removeItemAt(index);
}
if (source == acceptButton)
{
if (source == addButton)
{
//Add new song to array
songBox.addItem(newSong);
//Enable and disable appropriate buttons
addButton.setEnabled(true);
editButton.setEnabled(true);
deleteButton.setEnabled(true);
acceptButton.setEnabled(false);
cancelButton.setEnabled(false);
exitButton.setEnabled(true);
}
if (source == editButton)
{
//Make text fields uneditable
descriptionField.setEditable(false);
artistField.setEditable(false);
albumField.setEditable(false);
priceField.setEditable(false);
//Set new text
selection.setSongName(descriptionField.getText());
selection.setSongArtist(artistField.getText());
selection.setSongAlbum(albumField.getText());
selection.setSongPrice(priceField.getText());
songBox.addItem(selection);
//Enable and disable appropriate buttons
addButton.setEnabled(true);
editButton.setEnabled(true);
deleteButton.setEnabled(true);
acceptButton.setEnabled(false);
cancelButton.setEnabled(false);
exitButton.setEnabled(true);
}
}
if (source == cancelButton)
{
//Enable and disable appropriate buttons
addButton.setEnabled(true);
editButton.setEnabled(true);
deleteButton.setEnabled(true);
acceptButton.setEnabled(false);
cancelButton.setEnabled(false);
exitButton.setEnabled(true);
//Make text fields uneditable
descriptionField.setEditable(false);
artistField.setEditable(false);
albumField.setEditable(false);
priceField.setEditable(false);
}
if (source == exitButton) {
System.exit(0);
}
}
The program currently compiles and runs. The add and edit buttons do what they intend, but the accept and cancel buttons do not. When chosen, they don't do anything at all. Text fields remain editable and the accept and cancel buttons remain enabled while all other buttons remain disabled.
Update: The cancel button works to make the correct items enabled or disabled, but any changes made are not reset immediately, you have to toggle the combo box.
I understand now that 'source' can't equal two button inputs at the same time. However, the accept button has to do two different things depending on whether the user first selected add or edit, and I don't know how to handle that.
Your code looks like this:
if (source == acceptButton)
{
// Irelevant code removed.
if (source == cancelButton)
{
// This code is newer run, because you require first that source
// is==acceptButton and here you require that source==cancelButton.
}
}
But a better solution, is to have a method for each button, instead of looking at the event source. If you are using java 8(And you should be) have a look at http://www.codejava.net/java-core/the-java-language/java-8-lambda-listener-example
Trying to build my first Java MySQL CRUD application using BlueJ. I can run the application and can write data to MySQL database. However when I run a search function I get the Java .NullPointerException. I've done or attempted to do a stack trace referring to the following methods
displayBookDetails()
actionPerformed()
and cannot see where .SearchBookScreen would be set null?
As per What is a NullPointerException, and how do I fix it?
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at SearchBookScreen.displayBookDetails(SearchBookScreen.java:609)
at SearchBookScreen.actionPerformed(SearchBookScreen.java:393)
And here's an excerpt of source code as i was limited to the 30000 character limited
/**
* Search for books. Search for books based
* upon book title.
*/
private void searchForBooks()
{
// Call the bookSearch() method in DataBaseHandler Class
// This method returns a reference to a ResultSet object.
rs = DataBaseHandler.bookSearch(title);
// Set recordCount to 0
recordCount = 0;
} // End searchForBooks()
/**
* Display the book details in the result set on the form.
*/
private void displayBookDetails()
{
// Clear whatever might be on the form when this method
// might have been previously called
clearForm();
// Lots of methods which follow which require exception-
// handling code, e.g. next(), previous(), getString(), etc..
try
{
// The ResultSet many have 0, 1 or more records
// These need to be displayed on the form
// When recordCount is 0 ...
if ( recordCount == 0 )
{
// Try to advance the ResultSet pointer
if ( rs.next()== true )
{
// There must be at least one record in ResultSet if
// we are in here, so set recordsFound to true
recordsFound = true;
// Read the contents of each item in the ResultSet
isbn = rs.getString("isbnNo");
title = rs.getString("bookTitle");
author = rs.getString("author");
price = rs.getFloat("price");
// Add 1 to recordCount
recordCount++;
// Enable the Update and Delete buttons
updateButton.setEnabled (true);
deleteButton.setEnabled (true);
// Enable the Next and Previous Buttons
nextButton.setEnabled (true);
previousButton.setEnabled (true);
}
else
....
Line 609:
if ( rs.next()== true )
My ActionPerformed Class
/**
* Implement the actionPerformed() method
* in the ActionListener Interface Class
*
* #param An ActionEvent
*/
public void actionPerformed(ActionEvent event)
{
// Check to see if Search button pressed
if (event.getSource() == searchButton)
{
// Read the contents of the title text field
readBookTitle();
// Display an error message if there is no data in
// title text field
if (title.equals(""))
{
JOptionPane.showMessageDialog(frame,
"Error - you need to enter a Book Title");
}
else // OK to carry out search
{
// Search for book(s) based on the
// book title entered above
searchForBooks();
// Display Book(s)
displayBookDetails();
}
}
else // Check if Delete button pressed
if ( event.getSource() == deleteButton )
{
readBookIsbn(); // Read the book isbn from textfield
// Delete will be based on book isbn
// which is unique for every book.
// Call deleteBook() method in DataBaseHandler Class
int code = DataBaseHandler.deleteBook(isbn);
// code above will contain the total number of records
// deleted, which will be either 0 (none) or 1
if (code == 0) // If 0, means nothing deleted
{
// Display error message
JOptionPane.showMessageDialog(frame,
"No record found for deletion.");
}
else // Otherwise, there must have been a deletion
{
// Display message
JOptionPane.showMessageDialog(frame,
code + " Record(s) deleted from BOOK Table");
// Disable Update and Delete buttons
updateButton.setEnabled (false);
deleteButton.setEnabled (false);
}
// Clear the form
clearForm();
}
else // Check if Update button pressed
if (event.getSource() == updateButton )
{
// Before we read the current data off the form,
// it's important to make a copy of the isbn, This is
// necessary as the Update code in the
// DataBaseHandler Class invloves searching the Table based
// on the primary key field which is the isbn number.
// The user may have changed the isbn code on the screen,
// and we want to make sure we search based on the original
// isbn code.
oldIsbn = isbn;
// Read data from form
readDataFromForm();
// Update BOOKS Table with new data
upDateBooksTable();
}
else // Check if Next button pressed
if ( event.getSource() == nextButton )
{
// Set nextButtonPressed to true
nextButtonPressed = true;
// Make sure Delete and Update buttons
// are enabled
deleteButton.setEnabled (true);
updateButton.setEnabled (true);
// Display book details
displayBookDetails();
}
else // Check if Previous button pressed
if ( event.getSource() == previousButton )
{
// Set previousButtonPressed to true
previousButtonPressed = true;
// Make sure Delete and Update buttons
// are enabled
deleteButton.setEnabled (true);
updateButton.setEnabled (true);
// Display book details
displayBookDetails();
}
else // Check to see if Clear button was pressed
if (event.getSource() == clearButton)
{
// Clear the form
clearForm();
// Depending upon what happened previously, the
// Next and Previous buttons may be enabled.
// Shall always make sure they are disabled after we
// clear the form
nextButton.setEnabled (false);
previousButton.setEnabled (false);
}
else // Check if Back To Menu button pressed
if (event.getSource() == backButton)
{
// Dispose of this frame
frame.dispose();
// Close the database connection
closeConnection();
// Go back to MainMenu, by calling the
// Constructor method in the MainMenuScreen
// Class
new MainMenuScreen();
}
} // End actionPerformed()
Line 393:
displayBookDetails();
Many thanks!
your DatabaseHandler in method searchForBook() does not find any books, so the following assignment sets rs to null:
rs = DataBaseHandler.bookSearch(title)
since method invocation on an object, which is null will always NullPointerException, your condition in the if-statement of line 609 results in a NullPointerException.
if ( rs.next() == true ) // rs is null --> NullPointerException
change your condition to
if ( rs != null && rs.next())
this way, you also check if your object of rs is not null AND if it's not null the condition is true, if rs.next() returns true.
I have a panel just with a Jtextfield that only accept numbers. So, when I press enter will load a user profile. this is just to see his profile.
What I want: When I press ENTER again all the profile will be cleared, and when I press the numbers and press ENTER again and load the profile again and again...
My problem: I pressed enter and the profile is cleared (Ok all fine), but when I enter the number and press the ENTER, The numbers are cleared and nothing happens, it is like a loop in matriculaTxt.addKeyListener(new KeyAdapter() { ... }
Sorry for my bad English.
private void matriculaTxtActionPerformed(java.awt.event.ActionEvent evt)
{
String matricula = matriculaTxt.getText().trim();
if (!matricula.matches("[0-9]+")) {
matriculaTxt.setText("");
} else {
fc = new FrequenciaController();
matriculaTxt.setEditable(false);
matriculaTxt.requestFocus();
fc.checkinManual(Integer.parseInt(matricula));
}
// the problem is here.
matriculaTxt.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
nomeTxt.setText("");
statusTxt.setText("");
imageLb.setIcon(null);
acessoLabel.setText("");
matriculaTxt.setText("");
observacaoTxt.setText("");
System.err.println("ENTER");
PendenciasTableModel ptm = new PendenciasTableModel();// vazio
pendenciasTabela.setModel(ptm);
matriculaTxt.setEditable(true);
matriculaTxt.requestFocus();
}
}
});
}
What I wanted to do was simple. The user types in the text field their numbers, pressing ENTER: their data are loaded. requestFocus() into the text field and it will not be editable anymore, because when I press Enter again the field will be editable but everything will be deleted, and so on.
First off, you should never use a KeyListener for this sort of thing. Consider instead using either a JFormattedTextField or using a DocumentFilter to prevent non-numeric entry. Next, you should use an ActionLIstener to have the JTextField accept and react to the user's pressing the Enter key.
Edit
You state:
my exact requirements is, when i press ENTER again all data will be cleaned for a new data be inserted.
Why not simply have in your JTextField's ActionLIstener:
#Override
public void actionPerformed(ActionEvent e) {
// get the text
JTextComponent textComp = (JTextComponent) e.getSource();
String text = textComp.getText();
// do what you want with text here
// clear the text
textComp.setText("");
}
Again, you should not use a KeyListener for any of this stuff.
Edit 2
If you want a multi-state action listener, one that reacts differently depending on the state of the program, then give it some if blocks to allow it to react to the state of the JTextField. If the field is empty, do one thing, if it has numbers, do another, if it has text, show a warning and clear it:
#Override
public void actionPerformed(ActionEvent e) {
// get the text
JTextComponent textComp = (JTextComponent) e.getSource();
String text = textComp.getText().trim(); // trim it to rid it of white space
if (text.isEmpty()) {
// code to show a profile
return; // to exit this method
}
// if we're here, the field is not empty
if (!text.matches("[0-9]+")) {
// show a warning message here
} else {
// numeric only data present
// do action for this state
}
// clear the text
textComp.setText("");
}
The key again is to not use a KeyListener, but rather to "listen" for the enter key press with the ActionListener only, but to react differently depending on the state of the program, here likely being depending on what content is present in the JTextField.
I think that your problem that the KeyListener it'll not trigger, it will not execute the code inside it, because whenever you press ENTER it will trigger the matriculaTxtActionPerformed then declared the KeyLister, so the ENTER will effect it.