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
Related
I'm trying to make a java quiz linked to an sqlite database from where it's getting the informations (Questions and answers).
Every quiz has n questions.
A question has 4 options.
A question can have more than one true question.
so My database tables are:
Quiz(id_quiz, quiz_name)
Question (id_question, question, #id_quiz)
Answer (id_answer, statut, answer, #id_question)
So I created a first frame to select the quiz that we want to pass, it's working with a function that's calling the new Frame depending on the selected quiz.
My problem is when I compare the selected answers with the true answer that must be selected.
this is my code:
public boolean compare(List<Integer> trueAnswer, List<Integer> selected){
if (trueAnswer.equals(selected)){
return true;
} else {
return false;
}
}
The first step is to get the question in the jLabel, and the answers of that question too:
public List<Answer> showQuestion(int index){
in = fillQuestion(idQ).get(index).getIdQuestion();
jQuestion.setText(fillQuestion(idQ).get(index).getQuestion());
try {
con = DriverManager.getConnection("jdbc:sqlite:myflightdb.db", "", "");
String sql2 = ("select r.id_answer ,r.answer, r.statut from question q, answer r where q.id_question = ? and r.id_question = q.id_question ;");
PreparedStatement psmt2;
psmt2 = con.prepareStatement(sql2);
psmt2.setInt(1, in);
List<Answer> listRep = new ArrayList<Answer>();
rs2 = psmt2.executeQuery();
while(rs2.next()){
int idR = rs2.getInt("id_answer");
String rep = rs2.getString("answer");
String statut = rs2.getString("statut");
Reponse r = new Reponse(idR, rep, statut);
listRep.add(r);
}
return listRep;
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return null;
}
the function getTrueAnswer is made in order to get the list of true answers for question:
public List<Integer> getTrueAnswer(int index){
int idquestion;
idquestion = fillQuestion(idQ).get(index).getIdQuestion();
List<Integer> rep = new ArrayList<Integer>();
try {
con = DriverManager.getConnection("jdbc:sqlite:/Users/gate11/Desktop/MyFlight/myflightdb.db", "", "");
String sql = "select r.id_reponse from Reponse r where r.id_question = ? and r.statut like 'true';";
PreparedStatement psmt = con.prepareStatement(sql);
psmt = con.prepareStatement(sql);
psmt.setInt(1, idquestion);
rs = psmt.executeQuery();
while (rs.next()){
int idTrueAnswer= rs.getInt("id_reponse");
rep.add(idTrueAnswer);
}
//JOptionPane.showMessageDialog(null, Arrays.toString(rep.toArray()), "Selected IDs", JOptionPane.INFORMATION_MESSAGE);
return rep;
} catch (Exception e){
System.out.println(""+e.getMessage());
}
return null;
}
The button next must compare the selected jCheckBoxes with the true questions, if it's the same, the mark must be positif (so I can add the point to the result) or add 0 if the user doesn't choose the true one.
The problem is for the first time, it's working (I made the JOptionPanes to see the lists) so if I selected the first question, I have the selected is [1] and the true answer is [2]
but in the second question, if I select 1 I have the list is [1,1] for the third one [1,1,1] the fourth [1,1,1,1] etc ...
And I don't have any loop I can't find the problem.
If there is any idea please don't hesitate.
P.S: I did the 4 checkboxes because when I tried to add it in a for loop like that:
for (Answer a:listRep){
JcheckBox mycheck = new JcheckBox();
mycheck.setText(a.getQuestion());
mypanel.add(mycheck);
}
I found the problem, the itemListener must be added to the jCheckBoxes in the initialisation of the components.
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.
I am trying to learn Java so I apologize if this is a rookie question. I have researched enough before asking this question here. I appreciate your time and guidance here.
I have written a simple application where I am asking user to enter information like "Serverprocessorspeed", "RAM" etc
I need the information entered by the user in the fields "Serverprocessorspeed", "RAM" to be passed to Action Listener. These values are in turn sent to a database server.
Cloudbroker() {
f1 = new JFrame("Cloud Broker");
serverprocessorspeed = new JLabel("serverprocessorspeed :");
RAM = new JLabel("RAM :");
serverstorage = new JLabel("serverstorage :");
latency = new JLabel("latency :");
Region = new JLabel("Region");
txtserverprocessorspeed = new JTextField(60);
txtRAM = new JTextField(60);
txtserverstorage = new JTextField(60);
txtlatency = new JTextField(60);
txtRegion = new JTextField(60);
btnClose = new JButton("Close");
btnSave = new JButton("Save");
btnDelete = new JButton("Delete");
btnUpdate = new JButton("Update");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The information you entered has been saved");
Connection conn1 = null;
try {
String dbURL1 =
"jdbc:sqlserver://localhost\\SQLEXPRESS:1433;"
+ "databaseName=dbcloudbroker;user=XXX;password=XXXX";
System.out.println("this is connection inside the SAVE button");
conn1 = DriverManager.getConnection(dbURL1);
Statement stmt1 = conn1.createStatement();
// I need these values to be the ones the user
// enters in the feilds serverprocessorspeed and RAM.
stmt1.executeUpdate(
"INSERT INTO cloudbrokertable " + "VALUES(XXXX, XXXXX)");
} catch (SQLException e1) {
e1.printStackTrace();
} finally {
try {
if (conn1 != null && !conn1.isClosed()) {
conn1.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Based upon the suggestion I received, I edited my code accordingly
String speed = txtserverprocessorspeed.getText();
String ram = txtRAM.getText();
String storage = txtserverstorage.getText();
String latency = txtlatency.getText();
String region = txtRegion.getText();
System.out.println(speed);
stmt1.executeUpdate("INSERT INTO cloudbrokertable VALUES ('"+speed +"','"+ram+"','"+storage+"','"+latency+"','"+region+"')");
Now get the following error - com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near ')'.
The value is correctly passed into the variable speed and I can print it out.
I need the information entered by the used in the fields "Serverprocessorspeed", "RAM" to be passed to Action Listener. These values are in turn sent to a database server.
No, you don't, this isn't how this works (sorry). But, based on you code snippet, I would suggest you already have access to the information you need, for example...
btnSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ram = txtRAM.getText();
String speed = txtserverprocessorspeed.getText();
String storage = txtserverstorage.getText();
String latency = txtlatency.getText();
String region = txtRegion.getText();
//...
It's the problem with your SQL statement. You need to check if it does work.
Simply open your DB to test it with a sample statement like:
INSERT INTO cloudbrokertable VALUES ('100','DDR2','500','1000','US')
If this doesn't work it means you need to fix your statement.
I hope this help.
This is actually a re-do of an older question of mine that I have completely redone because my old question seemed to confuse people.
I have written a Java program that Queries a database and is intended to retrieve several rows of data. I have previously written the program in Informix-4GL and I am using a sql cursor to loop through the database and store each row into a "dynamic row of record". I understand there are no row of records in Java so I have ended up with the following code.
public class Main {
// DB CONNECT VARIABLE ===========================
static Connection gv_conn = null;
// PREPARED STATEMENT VARIABLES ==================
static PreparedStatement users_sel = null;
static ResultSet users_curs = null;
static PreparedStatement uinfo_sel = null;
static ResultSet uinfo_curs = null;
// MAIN PROGRAM START ============================
public static void main(String[] args) {
try {
// CONNECT TO DATABASE CODE
} catch(Exception log) {
// YOU FAILED CODE
}
f_prepare(); // PREPARE THE STATEMENTS
ArrayList<Integer> list_id = new ArrayList<Integer>();
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<Integer> list_info = new ArrayList<String>();
ArrayList<String> list_extra = new ArrayList<String>();
try {
users_sel.setInt(1, 1);
users_curs = users_sel.executeQuery();
// RETRIEVE ROWS FROM USERS
while (users_curs.next()) {
int lv_u_id = users_curs.getInt("u_id");
String lv_u_name = users_curs.getString("u_name");
uinfo_sel.setInt(1, lv_u_id);
uinfo_curs = uinfo_sel.executeQuery();
// RETRIEVE DATA FROM UINFO RELATIVE TO USER
String lv_ui_info = uinfo_curs.getString("ui_info");
String lv_ui_extra = uinfo_curs.getString("ui_extra");
// STORE DATA I WANT IN THESE ARRAYS
list_id.add(lv_u_id);
list_name.add(lv_u_name);
list_info.add(lv_ui_info);
list_extra.add(lv_ui_extra);
}
} catch(SQLException log) {
// EVERYTHING BROKE
}
// MAKING SURE IT WORKED
System.out.println(
list_id.get(0) +
list_name.get(0) +
list_info.get(0) +
list_extra.get(0)
);
// TESTING WITH ARBITRARY ROWS
System.out.println(
list_id.get(2) +
list_name.get(5) +
list_info.get(9) +
list_extra.get(14)
);
}
// PREPARE STATEMENTS SEPARATELY =================
public static void f_prepare() {
String lv_sql = null;
try {
lv_sql = "select * from users where u_id >= ?"
users_sel = gv_conn.prepareStatement(lv_sql);
lv_sql = "select * from uinfo where ui_u_id = ?"
uinfo_sel = gv_conn.prepareStatement(lv_sql)
} catch(SQLException log) {
// IT WON'T FAIL COZ I BELIEEEVE
}
}
}
class DBConn {
// connect to SQLite3 code
}
All in all this code works, I can hit the database once, get all the data I need, store it in variables and work with them as I please however this does not feel right and I think it's far from the most suited way to do this in Java considering I can do it with only 15 lines of code in Informix-4GL.
Can anyone give me advice on a better way to achieve a similar result?
In order to use Java effectively you need to use custom objects. What you have here is a lot of static methods inside a class. It seems that you are coming from a procedural background and if you try to use Java as a procedural language, you will not much value from using it. So first off create a type, you can plop it right inside your class or create it as a separate file:
class User
{
final int id;
final String name;
final String info;
final String extra;
User(int id, String name, String info, String extra)
{
this.id = id;
this.name = name;
this.info = info;
this.name = name;
}
void print()
{
System.out.println(id + name + info + extra);
}
}
Then the loop becomes:
List<User> list = new ArrayList<User>();
try {
users_sel.setInt(1, 1);
users_curs = users_sel.executeQuery();
// RETRIEVE ROWS FROM USERS
while (users_curs.next()) {
int lv_u_id = users_curs.getInt("u_id");
String lv_u_name = users_curs.getString("u_name");
uinfo_sel.setInt(1, lv_u_id);
uinfo_curs = uinfo_sel.executeQuery();
// RETRIEVE DATA FROM UINFO RELATIVE TO USER
String lv_ui_info = uinfo_curs.getString("ui_info");
String lv_ui_extra = uinfo_curs.getString("ui_extra");
User user = new User(lv_u_id, lv_u_name, lv_ui_info, lv_ui_extra);
// STORE DATA
list.add(user);
}
} catch(SQLException log) {
// EVERYTHING BROKE
}
// MAKING SURE IT WORKED
list.get(0).print();
This doesn't necessarily address the number of lines. Most people who use Java don't interact with databases with this low-level API but in general, if you are looking to get down to the fewest number of lines (a questionable goal) Java isn't going to be your best choice.
Your code is actually quite close to box stock JDBC.
The distinction is that in Java, rather than having a discrete collection of arrays per field, we'd have a simple Java Bean, and a collection of that.
Some examples:
public class ListItem {
Integer id;
String name;
Integer info;
String extra;
… constructors and setters/getters ellided …
}
List<ListItems> items = new ArrayList<>();
…
while(curs.next()) {
ListItem item = new ListItem();
item.setId(curs.getInt(1));
item.setName(curs.getString(2));
item.setInfo(curs.getInfo(3));
item.setExtra(curs.getString(4));
items.add(item);
}
This is more idiomatic, and of course does not touch on the several frameworks and libraries available to make DB access a bit easier.
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()));