I have a panel that shows a list of patients (ID/names/age). I have a jlist that when i click the patient it links the data of the patient to the textfields in my panel.
The problem: When im trying to update patient information i get a nullpointerexception for my age JFormattedTextField, ONLY when i do not click the age text field before hitting update.
To verify
1. All text fields empty
2. i click a patient, it updates the textfields with the patient info
3. i change say patient ID to something different and click update -> nullpointerexception
but if i instead click the patient, and then just click the age JFTF and then hit update, it reads the data perfectly fine.
Is there a way to "click" the textfield??
my code = when i click the jlist
int patientIndex = patientList.getSelectedIndex();
if (patientIndex == -1) {
return;
}
Object info = listModel.get(patientIndex);
String infoString = (String) info;
StringTokenizer st = new StringTokenizer(infoString);
idTF.setText(st.nextToken());
if (idTF.getText().equals("Empty")) {
idTF.setText("");
return;
}
firstNameTF.setText(st.nextToken());
lastNameTF.setText(st.nextToken());
ageTF.setText(st.nextToken());
-
String fName, lName, id, id2; // For now the ID will be name+age
int age;
Patient p = new Patient();
boolean gender;
// attempts to read the text fields
try {
fName = firstNameTF.getText();
lName = lastNameTF.getText();
id = idTF.getText();
age = ((Number) ageTF.getValue()).intValue();
System.out.println("age = " + age);
} catch (NullPointerException ex) {
System.out.println(ex.getMessage());
statusLabel.setText("All fields marked by a * are requried!");
}
I was using the wrong function to add the age to the age field. Since it is formatted, i must use setValue().
old code
ageTF.setText(st.nextToken());
ageTF.setValue(Integer.valueOf(st.nextToken()));
Related
I want to create a simple reservation application, like when you want to book movie ticket online, except this is a much simplified version.
I have a class names reservation with 8 toggle buttons and 1 button, the user will get to input number of seat they want to book in another class, let's just say 4.
In reservation, after the user choose 4 seats, the rest of the toggle button will be disabled to prevent user from choosing more seats. The user will then click the save button, and the data will then be inputted in the Database. Next time when another user open reservation, all of the toggle buttons will be re-enabled except those 4 seats previous user has booked earlier, obviously.
Everything is working so far except the part that i bold.
Here's my code :
private static final JToggleButton[] btn = new JToggleButton[8];
private int totalrow, a;
java.sql.Connection connection = null;
Statement statement4 = null;
ResultSet resultSet = null;
private void formWindowActivated(java.awt.event.WindowEvent evt) { // This is where i load the information that has been saved in the database before.
try {
connection = DriverManager.getConnection("jdbc:derby:
statement4 = (Statement) connection.createStatement();
resultSet = statement4.executeQuery("SELECT reservationid, seatno, validator FROM reservation WHERE reservationid = '" + time.id + "'");
String seatno, validator, rsid, id;
btn[0] = seat1;
btn[1] = seat2;
btn[2] = seat3;
btn[3] = seat4;
btn[4] = seat5;
btn[5] = seat6;
btn[6] = seat7;
btn[7] = seat8;
int i = 0;
while(resultSet.next()){
seatno = resultSet.getString("seatno");
validator = resultSet.getString("validator");
rsid = resultSet.getString("reservationid");
if(seatno.equals(btn[i].getText()) && validator.equals("reserved")){ //checking if seat i is reserved
btn[i].setSelected(true);
}
else{
btn[i].setSelected(false);
}
i++;
}
} catch (SQLException ex) {
Logger.getLogger(seat.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void actionPerformed(ActionEvent e) { // This actionlistener is used to count, if User has choose 4 seats, the code will disable the rest of the button
try {
connection = DriverManager.getConnection("jdbc:derby://localhost:1527/Project","root","root");
statement = (Statement) connection.createStatement();
btn[0] = seat1;
btn[1] = seat2;
btn[2] = seat3;
btn[3] = seat4;
btn[4] = seat5;
btn[5] = seat6;
btn[6] = seat7;
btn[7] = seat8;
a = 0;
for(JToggleButton btns : btn){
if (btns.isSelected()){
a++;
System.out.println(a);
if (! btns.isSelected()){
System.out.println(a);
a--;
}
}
}
for(JToggleButton btns : btn){
if (a >= Integer.parseInt(BookingUI.passenger)){ // This is number of Passenger taken from another class. In this case is 4.
if(! btns.isSelected()){
btns.setEnabled(false);
}
}
else{
btns.setEnabled(true);
}
}
} catch (SQLException ex) {
Logger.getLogger(seat.class.getName()).log(Level.SEVERE, null, ex);
}
}
Regarding my title, based on my current code and logic, it might not be possible to re-enable the toggle button. So the better way to do it might be to use another logic to disable the toggle button instead.
In the image, seat 1,4,5,8 are chosen by the user. And the rest of the buttons are disabled
Since it's a long implementation, it's difficult to answer with a code solution. There for I will mention my suggestion here.
You have to declare your JToggleButton Array like this btn = new JToggleButton[8]; in a public static context where every class could access it. And when the user reserved a seat you should save the data to DB (or keep in the program memroy, eg : HashMap) on which user reserved the which seat.
After that when you loading the data from the Database you should loop through and get the booked seats which previously inserted and then by accessing that predefined JToggleButton Array and set each booked seat by doing this btns[i].setEnabled(false); (i for the booked index of the seat).
Hope this helps
i'm in making GUI application in netbeans for my college semester project (Market manager). we can add any product to the app and store the data as .txt file and file name is based on product code.
sample data in 1234.txt :
Product code : 1234
Name : Noodle
Price : $1000
Description : Instant noodle is not good for healthy
Expiry data : 12-01-2050
my question is how to read all file if there already added more of .txt file and read date in file and showing list of expired product to jtextArea as file name based on current date and button for remove all expired file.
private void okBtnActionPerformed(java.awt.event.ActionEvent evt) {
String code = txtCode.getText();
String name = txtName.getText();
String price = txtPrice.getText();
String expiry = txtExpiry.getText();
String quantity = txtQuantity.getText();
String description = txtDescription.getText();
int quant = Integer.parseInt(quantity);
try {
for (int i = 0; i < quant; i++) {
File file = new File("Product/"+code+i+".txt");
if (!file.exists()) {
file.createNewFile();
String content = "Code: " + code + i + "\r\nName: " + name + "\r\nPrice: RM." + price + "\r\nDescription: " + description + "\r\nExpiry Date: " + expiry;
FileWriter data = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(data);
bw.write(content);
bw.close();
JOptionPane.showMessageDialog(this, "Product Added");
txtCode.setText("");
txtName.setText("");
txtPrice.setText("");
txtExpiry.setText("");
txtQuantity.setText("");
txtDescription.setText("");
} else {
JOptionPane.showMessageDialog(this, "The Product Code Already Added");
break;
}
}
} catch (IOException e) {
}
}
this code for adding product
You start by separating responsibilities. You first create a class that represents a Product. In your current approach, you try to "model" a Product by a "set" of variables that somehow belong together.
Instead, create a class that has the corresponding fields; and a nice equals method for example.
Then you create a method that takes a String representing a filename. That method opens the file; reads the textual data and creates one Product object from that. Lets call that readSingleProduct().
Next: create a method that takes a String representing a directory for example. That method checks for all the text files in that directory and calls readSingleProduct() in order create Product objects; and in the end, that method would return some List<Product>.
And then, finally, you build your UI code that receives such a List of Product objects, and uses that as model for the actual UI components.
And a hint: you never go with empty catch blocks. You should at least print the exception there; ignoring errors is always a super-bad idea!
Hope that gets you going!
So I'm trying to make a save button to update the columns inside the database according to what's typed into their corresponding textfields, but I keep getting this error "Invalid operation at current cursor position". I can't figure out what's wrong since everything else is working. Can anyone help? Thanks in advance!
private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {
i = Integer.parseInt(txt_userid.getText( ));
s = txt_pass.getText( );
n = txt_name.getText( );
birthdate = txt_bdate.getText();
contactno = Integer.parseInt(txt_contact.getText());
age = Integer.parseInt(txt_age.getText());
email = txt_email.getText();
address = txt_address.getText();
gender = txt_gender.getText();
adult = Integer.parseInt(txt_adult.getText());
child = Integer.parseInt(txt_child.getText());
senior = Integer.parseInt(txt_senior.getText());
charge = Integer.parseInt(txt_charge.getText());
travelclass = txt_travelclass.getText();
luggage = txt_luggage.getText();
flightID = txt_flightid.getText();
departdate = txt_depardate.getText();
departtime = txt_departime.getText();
destination = txt_destination.getText();
arrivdate = txt_arrivdate.getText();
arrivtime = txt_arrivtime.getText();
try{
rs.updateInt("USERID",i);
rs.updateString("PASSWORD",s);
rs.updateString("USERNAME",n);
rs.updateInt("AGE",age);
rs.updateString("GENDER",gender);
rs.updateString("BIRTHDATE",birthdate);
rs.updateString("EMAIL",email);
rs.updateInt("CONTACTNO",contactno);
rs.updateString("ADDRESS",address);
rs.updateString("FLIGHTID", flightID);
rs.updateString("DEPARDATE", departdate);
rs.updateString("DEPARTIME", departtime);
rs.updateString("DESTINATION", destination);
rs.updateString("TRAVELCLASS", travelclass);
rs.updateString("LUGGAGE", luggage);
rs.updateInt("TOTALPAY", charge);
rs.updateInt("ADDPASSENGERSSENIOR", senior);
rs.updateInt("ADDPASSENGERSADULT", adult);
rs.updateInt("ADDPASSENGERSCHILD", child);
rs.updateString("ARRIVALDATE", arrivdate);
rs.updateString("ARRIVALTIME", arrivtime);
rs.updateRow( );
Refresh_RS_STMT();
ShowAll();
JOptionPane.showMessageDialog(AdminWindow.this,
"Record has been saved!");
}catch(SQLException err){
System.out.println(err.getMessage() );
}
}
Try to call the rs.next() before any usage of the ResultSet object. In fact a fresh ResultSet object have a pointer inside which points to -1 (none of the results by default), when you call the next() method for the first time it will point to the first row, if exists, and returns true, otherwise it will return false. each time you call it it will try to point to the next row and so on.
In my application on users profile page, user has:
Name: XYZ
Age: ##
Address: st.XYZ
and so on...
When an element is missing (example age) other row takes its place, so I can't hardcode the xpath of elements. What I want is:
I want to (print) extract entire table data and compare with actual.
So when I ask for "Name" as key it should give cell value infront of it as value of key.
What I tried:
I was able to get text of tr tags elements keeping td fixed. But for another user when some row is missing it fails or gives wrong value.
for (int i = 2; i < 58; i++) {
String actor_name = new WebDriverWait(driver, 30).until(ExpectedConditions
.elementToBeClickable(By.xpath(first_part+i+part_two))).getText();
System.out.print("\n"+"S.no. "+(i-1)+" "+actor_name);
try {
driver.findElement(By.xpath(first_part+i+part_two)).click();
new WebDriverWait(driver, 30).until(ExpectedConditions
.elementToBeClickable(By.partialLinkText("bio"))).click();
//driver.findElement(By.partialLinkText("bio")).click();
} catch (Exception e) {
// TODO: handle exception
System.out.println("Not a link");
}
Thread.sleep(5000);
System.out.print(" "+driver.findElement(By.xpath("//*[#id='overviewTable']/tbody/tr[3]/td[2]")).getText());
driver.get("http://www.imdb.com/title/tt2310332/fullcredits?ref_=tt_cl_sm#cast");
}
Above code works fine for top 3 actors on this page but fails for 4th because that doesn't have one row missing on bio page.
On the bio page there two columns in the table one has attribute other has its value. I want to make a collection with key value pair with key as attribute (value from left column) and its value as value from right column. So that I get the freedom of fetching the values by mentioning the attribute value.
I am using JAVA to write scripts.
Can you try out with following code and provide me with any concerns if you have any...
driver.get("http://www.imdb.com/title/tt2310332/fullcredits?ref_=tt_cl_sm#cast");
String height = "";
String actorName = "";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
List<WebElement> lstUrls = driver.findElements(By
.xpath("//span[#itemprop='name']/..")); // all a tags
List<String> urls = new ArrayList<>();
for (WebElement webElement : lstUrls) {
urls.add(webElement.getAttribute("href")); // saving all hrefs attached in each a tag
}
Map<String, String> actorHeightData = new HashMap<String, String>();
for (String string : urls) {
driver.get(string);
actorName = driver.findElement(
By.xpath(".//*[#id='overview-top']/h1/span")).getText(); // Getting actor's name
driver.findElement(By.xpath("//a[text()='Biography']")).click(); // Clicking Biography
try {
height = driver.findElement(
By.xpath("//td[.='Height']/following-sibling::td"))
.getText(); // Getting height
} catch (NoSuchElementException nsee) {
height = ""; // If height not found
}
actorHeightData.put(actorName, height); // Adding to map
}
You can create class PersonData with all nullable fields you need. But with not null getters.
for example
calss PersonData{
private String name;
public getName(){
if(name == null)
return "";
return name;
}
}
and store all persons in a List.
In you page you will ask person for field and always have something in table's cell.
I have the following functions to mark attendance of an employee:
public void updateDailyAttendance(ActionRequest areq, ActionResponse aRes) throws Exception {
int totalEmployees = EmployeeLocalServiceUtil.getEmployeesCount();
List<Employee> employeeAttendanceDetails = MISPortalActionUtil.getEmployeeData();
String datt = areq.getParameter("datt");
String Imatt = areq.getParameter("matt");
String yatt = areq.getParameter("yatt");
int Lmatt = Integer.parseInt(Imatt);
String matt = Integer.toString(Lmatt +1);
String dateOfAttendance = datt +"/"+ matt +"/"+ yatt;
SimpleDateFormat dateOfAttendanceFormat = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date_Of_Attendance = dateOfAttendanceFormat.parse(dateOfAttendance);
System.out.println("Today's attendance date is: " + date_Of_Attendance);
ArrayList<String> attNames = new ArrayList<String>();
for (Employee emp: employeeAttendanceDetails) {
long empId = emp.getEmpId();
String name = "updateattendance" + " " +Long.toString(emp.getEmpId());
System.out.println("updateattendance name : " + name);
String value = getAttendanceValue(areq,name);
System.out.println("updateattendance value : " + value);
long attPKey = CounterLocalServiceUtil.increment(Employee.class.getName());
Attendance newAttendanceInstance = new AttendanceImpl();
String checkAttMarkStatus = newAttendanceInstance.getAttStatus();
System.out.println("checkAttMarkStatus: " + checkAttMarkStatus);
//loop to mark the attendance if it has not been pre marked
if(checkAttMarkStatus != "Absent" || checkAttMarkStatus != "Half Day" ) {
newAttendanceInstance.setAttId(attPKey);
newAttendanceInstance.setAttDate(date_Of_Attendance);
newAttendanceInstance.setAttStatus(value);
newAttendanceInstance.setAttANStatus(value);
newAttendanceInstance.setAttFNStatus(value);
newAttendanceInstance.setEmpId(empId);
AttendanceLocalServiceUtil.addAttendance(newAttendanceInstance);
}//loop to mark the attendance if it has not been pre marked
}
}
/**
* The getAttendanceValue() is used to fetch parameter values and pass the values to updateDailyAttendance function
* #param areq
* #return
* #throws SystemException
*/
private String getAttendanceValue(ActionRequest areq, String paramName) {
Enumeration parameters = areq.getParameterNames();
System.out.println("updateattendance paramName : " + paramName);
while (parameters.hasMoreElements()) {
System.out.println("updateattendance paramName inside while : " + paramName);
String parameterName = parameters.nextElement().toString();
System.out.println("updateattendance paramName new : " + paramName);
System.out.println("the paramName " + paramName + " parameterName " + parameterName);
if (paramName.equals(parameterName)) {
return areq.getParameter(parameterName);
}
}
throw new IllegalStateException("Parameter updateattendance is not found");
}
In my jsp the list of employees is populated and user is allowed to mark attendance through radio button. This approach works well when I am marking attendance for all the employees.
But problem comes when I have pre marked attendance status.
Whenever a user applies for leave his attendance status is premarked and the attendance form for marking attendance for this employee is shown as marked and disabled.. So when I try to mark attendance when pre marked attendance exists, it doesnt mark attendance for other employees. ex. Suppose if the 4th entry is pre marked as absent, and I mark attendance for other employees, then only first three entries are added in the database and then it doesnt find the fourth entry and throws the illegal exception:
Parameter updateattendance is not found
How should I change my getAttendanceValue() function to suit my purpose?
EDIT:
The JSP part where I am fetching the values:
<label>Present</label><input type = "radio" name ='updateattendance <%=((Object[])search)[5]%>' value = "Present" />
<label>Absent</label><input type = "radio" name= 'updateattendance <%=((Object[])search)[5]%>' value = "Absent" />
IN the above code I have kept a check to see if it is pre marked. I have put the above code fragment in if-else block for pre marked attendance check
You're doing this:
Attendance newAttendanceInstance = new AttendanceImpl();
String checkAttMarkStatus = newAttendanceInstance.getAttStatus(); // most likely null or ""
System.out.println("checkAttMarkStatus: " + checkAttMarkStatus);
So I don't expect the correct status to be held by the object that you just created without any reference to previous state. My expectation is that checkAddMarkStatus is now "" (empty string) or null
Further you check for identity of strings, not equality (this is a huge difference in java:
if(checkAttMarkStatus != "Absent" || checkAttMarkStatus != "Half Day" ) {
You should rather use String.equal (and be aware of null values), but due to the issue described above, this will not help you without sorting out both issues. There might be more, but this is what I found on first sight.
Following the comments and your question update, I'm still missing to see the actual intent in the code. However, I'd advise to not use an exception like you do for a case that doesn't seem exceptional - rather use proper return values and check for these values - e.g. if someone never attended, have a value to signal this and react accordingly. If you throw an exception and don't catch it, you must expect things like you mention (e.g. half-executed methods)