So for a school project I'm doing, I am copying the same code and pasting it, just changing the Identifier name.
if (s1.isSelected()){
System.out.println("Hello");
String query = "update booking set s1 = 0 where bdate ='"+d+"';";
stmt.executeUpdate(query);
}
if (s2.isSelected()){
System.out.println("Hello");
String query = "update booking set s2 = 0 where bdate ='"+d+"';";
stmt.executeUpdate(query);
}
if (s3.isSelected()){
System.out.println("Hello");
String query = "update booking set s3 = 0 where bdate ='"+d+"';";
stmt.executeUpdate(query);
}
How do I repeat this code for 100-120 times? Is there an easy way of doing this?
Thanks.
Read about
void putClientProperty(Object key, Object value);
and
Object getClientProperty(Object key);
Almost every GUI system, binary Win32 too, has similar concept to store specific data with/in component. This drastically eliminate stupid repeatable code, strange if
s series etc. For example
List<JCheckBox> boxes = ... ;
for(...){
JCheckBox box = ... // create, add listeners and position component by code
boxes.add(box);
box.putClientProperty("seat", anSeatObject );
}
when required, in event listener, or during save phase this information can be read;
Additional note on the margin: personally I prefer table with SeatsByDate, not hundreds of column. In your model querying for free seats is almost impossible. Because I prefer JPA, I will make entity
@Enitity
SeatsByDate {
@Id
int id;
@ManyToOne
ReserationDate date;
bool isReserved;
}
and then
SeatsByDate anSeatObject
So JPA is my personal preference, ClientProperty
may be simple string too.
List<JCheckBox> boxArray = new ArrayList<JCheckBox>();
boxArray.add(box1);
boxArray.add(box2);
//.....
for(int i = 0;i<boxArray.size();i++){
JCheckBox box = boxArray.get(i);
String indexStr = i + 1;
if(box.isSelected()){
System.out.println("Hello");
String query = "update booking set s" + indexStr+"= 0 where bdate ='"+d+"'";
stmt.executeUpdate(query);
}
}
Make use of loop statements and functions to achieve that. You could use FOR statement in a case where you know how many repetitions you need.
https://en.wikipedia.org/wiki/Control_flow#Loops
Assuming you have an array or collections with all the seats, you could make a function to update a specific seat passed as an argument and call it as many times you want within the FOR statement. It would be something like this:
public void updateBooking(Seat seat) {
// You'd need to add here some stuff like db connection
if (seat.isSelected()){
System.out.println("Hello");
String query = "update booking set " + seat.getId() + " = 0 where bdate ='" + d + "';";
stmt.executeUpdate(query);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.