How to update row selected by id column? - java

This a 'form'with textfields where admin can update
//For Update
public AdminCreateQnsPanel(JFrame mf, QuizDetails q, int set, String topic) {
super(mf);
System.out.println("**** admin create qns panel *"+ q.getQuestionNo());
System.out.println("**** admin create qns panel *"+ q.getQuestionDesc());
System.out.println("**** admin create qns panel *"+ q.getOption1());
System.out.println("**** admin create qns panel *"+ q.getOption2());
JLabel lblSet = new JLabel("Set 1");
lblSet.setFont(new Font("Tahoma", Font.BOLD, 30));
lblSet.setBounds(29, 160, 141, 28) ;
add(lblSet);
JLabel lblQnsDesc = new JLabel("Question Description :");
lblQnsDesc.setFont(new Font("Tahoma", Font.BOLD, 16));
lblQnsDesc.setBounds(76, 270, 181, 20);
add(lblQnsDesc);
txtfQnsDesc = new JTextField();
txtfQnsDesc.setColumns(10);
txtfQnsDesc.setBounds(76, 306, 639, 26);
add(txtfQnsDesc);
txtfQnsDesc.setText(q.getQuestionDesc());
JLabel lblOp1 = new JLabel("Option 1 :");
lblOp1.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp1.setBounds(76, 365, 103, 20);
add(lblOp1);
txtfOp1 = new JTextField();
txtfOp1.setColumns(10);
txtfOp1.setBounds(218, 362, 146, 26);
add(txtfOp1);
txtfOp1.setText(q.getOption1());
JLabel lblOp2 = new JLabel("Option 2 :");
lblOp2.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp2.setBounds(76, 418, 103, 20);
add(lblOp2);
txtfOp2 = new JTextField();
txtfOp2.setColumns(10);
txtfOp2.setBounds(218, 415, 146, 26);
add(txtfOp2);
txtfOp2.setText(q.getOption2());
JLabel lblOp3 = new JLabel("Option 3 :");
lblOp3.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp3.setBounds(76, 468, 103, 20);
add(lblOp3);
txtfOp3 = new JTextField();
txtfOp3.setColumns(10);
txtfOp3.setBounds(218, 465, 146, 26);
add(txtfOp3);
txtfOp3.setText(q.getOption3());
JLabel lblOp4 = new JLabel("Option 4 :");
lblOp4.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp4.setBounds(76, 515, 103, 20);
add(lblOp4);
txtfOp4 = new JTextField();
txtfOp4.setColumns(10);
txtfOp4.setBounds(218, 512, 146, 26);
add(txtfOp4);
txtfOp4.setText(q.getOption4());
JLabel lblCorrAns = new JLabel("Correct Answer :");
lblCorrAns.setFont(new Font("Tahoma", Font.BOLD, 16));
lblCorrAns.setBounds(76, 581, 151, 20);
add(lblCorrAns);
txtfCorrAns = new JTextField();
txtfCorrAns.setColumns(10);
txtfCorrAns.setBounds(218, 578, 146, 26);
add(txtfCorrAns);
txtfCorrAns.setText(q.getCorrectAnswer());
JButton button = new JButton("Add");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedAdd();
//actionPerformedOk();
}
});
button.setFont(new Font("Tahoma", Font.BOLD, 16));
button.setBounds(428, 622, 115, 29);
add(button);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminQuizOverallPanel(myFrame, set, topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnCancel.setFont(new Font("Tahoma", Font.BOLD, 16));
btnCancel.setBounds(712, 622, 115, 29);
add(btnCancel);
JLabel lblQnsNo = new JLabel("Question No. : ");
lblQnsNo.setFont(new Font("Tahoma", Font.BOLD, 16));
lblQnsNo.setBounds(76, 234, 151, 20);
add(lblQnsNo);
txtfQnsNo = new JTextField();
txtfQnsNo.setBounds(218, 228, 146, 26);
add(txtfQnsNo);
txtfQnsNo.setColumns(10);
txtfQnsNo.setText(new Integer(q.getQuestionNo()).toString());
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedUpdate();
} });
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 16));
btnUpdate.setBounds(572, 622, 115, 29);
add(btnUpdate);
}
//Create
private void actionPerformedAdd() {
// retrieve the user input from the text box/area provided
if (validateInput()) {
//amtSpend = Double.parseDouble(txtAmount.getText());
// create an object of expenses based on the input values
//Debugging? -> System.out.println(topic);
//***Refer to QuizDetails Entity Class for its constructor
QuizDetails e1 = new QuizDetails(Integer.parseInt(txtfQnsNo.getText()), txtfQnsDesc.getText(), txtfOp1.getText(),
txtfOp2.getText(), txtfOp3.getText(), txtfOp4.getText(), txtfCorrAns.getText(), topic, set);
// insert to database and check return value
if (QuizDetailsDA.createQuizDetails(e1)) { //Call Create method from QuizDetailsDA
System.out.print("Ok");
JOptionPane.showMessageDialog(myFrame,
"Record created successfully", "Alert",
JOptionPane.INFORMATION_MESSAGE);
// reset text field for next record.
txtfQnsNo.setText("");
txtfQnsDesc.setText("");
txtfOp1.setText("");
txtfOp2.setText("");
txtfOp3.setText("");
txtfOp4.setText("");
txtfCorrAns.setText("");
JPanel contentPane = new AdminQuizOverallPanel(myFrame, set,topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
} else
{
System.out.print("Error");
JOptionPane.showMessageDialog(myFrame,
"Database Error. Record not created.", "Alert",
JOptionPane.ERROR_MESSAGE);
}
}
}
private boolean validateInput() {
boolean result = false;
String msg = "";
result = true;
/*int msgType = JOptionPane.ERROR_MESSAGE;
// retrieve the user input from the text box/area provided
String dateSpend = txtDate.getText();
String cat = txtCategory.getText();
String amt = txtAmount.getText();
String cont = txtContent.getText();
if (dateSpend.length() != 10)
msg += "Please enter date in DD-MM-YYYY format.\n";
if (cat.length() == 0)
msg += "Please enter category.\n";
try {
Double.parseDouble(amt); // convert to double for amount
} catch (NumberFormatException e) {
msg += "Plese enter amount in decimal numbers.\n";
}
if (cont.length() == 0)
msg += "Please enter content.\n";
if (msg.length() == 0)
result = true;
else
JOptionPane.showMessageDialog(myFrame, msg, "Alert", msgType);
*/
return result;
}
//Update
public AdminCreateQnsPanel(JFrame mf,String action, QuizDetails e1){
this(mf, action);
txtfQnsNo.setText(new Integer(e1.getQuestionNo()).toString());
txtfQnsDesc.setText(e1.getQuestionDesc());
txtfOp1.setText(e1.getOption1());
txtfOp2.setText(e1.getOption2());
txtfOp3.setText(e1.getOption3());
txtfOp4.setText(e1.getOption4());
txtfCorrAns.setText(e1.getCorrectAnswer());
quizdetails = e1;
}
public AdminCreateQnsPanel(JFrame mf, String action) {
super(mf);
}
public void actionPerformedUpdate(){
int qnsNo = Integer.parseInt(txtfQnsNo.getText());
String qnsDesc = txtfQnsDesc.getText();
String op1 = txtfOp1.getText();
String op2 = txtfOp2.getText();
String op3 = txtfOp3.getText();
String op4 = txtfOp4.getText();
String corrAns = txtfCorrAns.getText();
//***Refer to QuizDetails Entity Class for its constructor
QuizDetails e1 = new QuizDetails(id1,qnsNo, qnsDesc, op1, op2, op3, op4, corrAns);
//Testing -> System.out.println("action performed update " + e1.getQuestionNo());
if(QuizDetailsDA.updateQuizDetails(e1)){ //Call Update method from QuizDetailsDA
JOptionPane.showMessageDialog(myFrame, "Record updated successfully", "Alert", JOptionPane.INFORMATION_MESSAGE);
txtfQnsNo.setEditable(false);
txtfQnsDesc.setEditable(false);
txtfOp1.setEditable(false);
txtfOp2.setEditable(false);
txtfOp3.setEditable(false);
txtfOp4.setEditable(false);
txtfCorrAns.setEditable(false);
}
else{
JOptionPane.showMessageDialog(myFrame, "Database Error. Record not updated.", "Alert", JOptionPane.ERROR_MESSAGE);
}
}
This is the class where JTable is shown.
package studyHelperApp.ui;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import model.QuizDetailsTableModel;
import studyHelperApp.dataAccess.QuizDetailsDA;
import studyHelperApp.entity.QuizDetails;
import javax.swing.JButton;
import javax.swing.JFrame;
import studyHelpersApp.ui.MasterPanel;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.ListSelectionModel;
import java.awt.Color;
public class AdminQuizOverallPanel extends MasterPanel {
private JTextField txtfSearch;
private JTable table;
private int set;
private String topic;
public static int id1;
private int id;
private void setTableModelFromDB(){
ArrayList <QuizDetails> result = QuizDetailsDA.retrieveAllQuizDetails(set,topic); //Call method from QuizDetailsDA
QuizDetailsTableModel model = new QuizDetailsTableModel(result);
table.setModel(model);
}
public void loadDataTable(){
setTableModelFromDB();
}
/**
* Create the panel.
* #wbp.parser.constructor
*/
public AdminQuizOverallPanel(JFrame mf) {
super(mf);
initComponents();
setBounds(100, 100, 900, 750);
setLayout(null);
JLabel lblDisplay = new JLabel("");
lblDisplay.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblDisplay.setBounds(550, 200, 287, 20);
add(lblDisplay);
JLabel lblSet = new JLabel("Set ");
lblSet.setBounds(49, 189, 58, 31);
lblSet.setFont(new Font("Tahoma", Font.BOLD, 30));
add(lblSet);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(15, 246, 847, 225);
add(scrollPane);
table = new JTable();
loadDataTable();
scrollPane.setViewportView(table);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedDelete();
}
});
btnDelete.setFont(new Font("Tahoma", Font.BOLD, 16));
btnDelete.setBounds(637, 502, 115, 29);
add(btnDelete);
JButton btnSearch = new JButton("Search");
btnSearch.setFont(new Font("Tahoma", Font.BOLD, 16));
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0){
lblDisplay.setText("You searched for: "+txtfSearch.getText());
}
});
btnSearch.setBounds(744, 160, 93, 29);
add(btnSearch);
txtfSearch = new JTextField();
txtfSearch.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_ENTER)
lblDisplay.setText("You searched for: "+txtfSearch.getText());
}
});
txtfSearch.setBounds(550, 161, 194, 26);
add(txtfSearch);
txtfSearch.setColumns(10);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedUpdate();
}
});
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 16));
btnUpdate.setBounds(372, 502, 115, 29);
add(btnUpdate);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminCreateQnsPanel(myFrame, set ,topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnAdd.setFont(new Font("Tahoma", Font.BOLD, 16));
btnAdd.setBounds(135, 502, 115, 29);
add(btnAdd);
JButton btnBack = new JButton("<Back");
btnBack.setFont(new Font("Tahoma", Font.BOLD, 16));
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminQuizSetNoPanel(myFrame, topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnBack.setBounds(70, 555, 115, 29);
add(btnBack);
JLabel lblQuizID = new JLabel(topic);
lblQuizID.setFont(new Font("Tahoma", Font.BOLD, 30));
lblQuizID.setBounds(156, 189, 147, 31);
add(lblQuizID);
JLabel lblSetNo = new JLabel("");
lblSetNo.setFont(new Font("Tahoma", Font.BOLD, 30));
lblSetNo.setBounds(107, 189, 31, 31);
add(lblSetNo);
}
public AdminQuizOverallPanel(JFrame mf, int set, String topic) {
super(mf);
this.set = set;
this.topic = topic;
initComponents();
setBounds(100, 100, 900, 750);
setLayout(null);
JLabel lblDisplay = new JLabel("");
lblDisplay.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblDisplay.setBounds(550, 200, 287, 20);
add(lblDisplay);
JLabel lblSet = new JLabel("Set");
lblSet.setBounds(49, 189, 93, 31);
lblSet.setFont(new Font("Tahoma", Font.BOLD, 30));
add(lblSet);
JLabel lblSetNo = new JLabel(Integer.toString(set));
lblSetNo.setBounds(107, 189, 31, 31);
lblSetNo.setFont(new Font("Tahoma", Font.BOLD, 30));
add(lblSetNo);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(15, 246, 847, 225);
add(scrollPane);
table = new JTable();
loadDataTable();
scrollPane.setViewportView(table);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedDelete();
}
});
btnDelete.setFont(new Font("Tahoma", Font.BOLD, 16));
btnDelete.setBounds(611, 502, 115, 29);
add(btnDelete);
JButton btnSearch = new JButton("Search");
btnSearch.setFont(new Font("Tahoma", Font.BOLD, 16));
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0){
lblDisplay.setText("You searched for: "+txtfSearch.getText());
//findQuizDetails();
}
});
btnSearch.setBounds(744, 160, 93, 29);
add(btnSearch);
txtfSearch = new JTextField();
txtfSearch.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_ENTER)
lblDisplay.setText("You searched for: "+txtfSearch.getText());
}
});
txtfSearch.setBounds(550, 161, 194, 26);
add(txtfSearch);
txtfSearch.setColumns(10);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedUpdate();
}
});
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 16));
btnUpdate.setBounds(365, 502, 115, 29);
add(btnUpdate);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminCreateQnsPanel(myFrame, set ,topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnAdd.setFont(new Font("Tahoma", Font.BOLD, 16));
btnAdd.setBounds(123, 502, 115, 29);
add(btnAdd);
JButton btnBack = new JButton("<Back");
btnBack.setFont(new Font("Tahoma", Font.BOLD, 16));
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminQuizSetNoPanel(myFrame, topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnBack.setBounds(70, 555, 115, 29);
add(btnBack);
JLabel lblQuizID = new JLabel(topic);
lblQuizID.setFont(new Font("Tahoma", Font.BOLD, 30));
lblQuizID.setBounds(156, 189, 147, 31);
add(lblQuizID);
}
private void initComponents() {
// TODO Auto-generated method stub
}
//Delete
public void actionPerformedDelete(){
System.out.println("performed delete 1****");
int rowSelected = table.getSelectedRow();
System.out.println("performed delete 2 *****"+ rowSelected);
if(rowSelected >= 0){
int resp = JOptionPane.showConfirmDialog(myFrame, "Confirm Delete?", "Confirmation", JOptionPane.YES_NO_CANCEL_OPTION);
if(resp == JOptionPane.YES_OPTION){
int selRowDel = (Integer)table.getModel().getValueAt(rowSelected, 0);
QuizDetailsDA.deleteQuizDetails(selRowDel); //Call Delete method from QuizDetailsDA
//QuizDetailsDA.retrieveAllQuizDetails();
setTableModelFromDB();
}
else {
JOptionPane.showMessageDialog(myFrame, "No record selected", "Alert", JOptionPane.ERROR_MESSAGE);
}
}
}
//Update
public void actionPerformedUpdate(){
int rowSelected = table.getSelectedRow();
if(rowSelected >= 0){
int id = (Integer)table.getModel().getValueAt(rowSelected, 0);
id1 = id;
QuizDetails quizdt = QuizDetailsDA.retrieveQuizDetailsById(id);
//Testing -> System.out.println("**** action performed update **: " + quizdt.getQuestionNo());
//Call method from AdminCreateQnsPanel(JFrame mf, QuizDetails q, int set, String topic) constructor
JPanel contentPane = new AdminCreateQnsPanel(myFrame,quizdt, set, topic);
//After adding set and topic to this above constructor, cancel button is working in AdminCreateQnsPanel
myFrame.getContentPane().removeAll();
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
else {
JOptionPane.showMessageDialog(myFrame, "No record selected", "Alert", JOptionPane.ERROR_MESSAGE);
}
}
}
Data access package
//retrieve quiz by id
public static QuizDetails retrieveQuizDetailsById(int id) {
// declare local variables
QuizDetails quizdetails = null;
ResultSet rs = null;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - connect to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "SELECT * FROM QuizDetails WHERE id=?";
pstmt = db.getPreparedStatement(dbQuery);
// step 3 - execute query
try {
pstmt.setInt(1,id);
rs = pstmt.executeQuery();
if (rs.next()) { // first record found
quizdetails = convertToQuizDetails(rs);
}
} catch (Exception e) {
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return quizdetails;
}
private static QuizDetails convertToQuizDetails(ResultSet rs) throws SQLException {
QuizDetails quizdetails;
int id = rs.getInt("id");
//String quizID = rs.getString("quizID");
//int setNo = rs.getInt("setNo");
int questionNo = rs.getInt("questionNo");
String questionDesc = rs.getString("questionDesc");
String option1 = rs.getString("option1");
String option2 = rs.getString("option2");
String option3 = rs.getString("option3");
String option4 = rs.getString("option4");
String correctAnswer = rs.getString("correctAnswer");
quizdetails = new QuizDetails(id, questionNo, questionDesc, option1, option2, option3, option4, correctAnswer );
return quizdetails;
}
//Update
public static boolean updateQuizDetails(QuizDetails quizdt) {
//declare local variables
boolean success = false;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
System.out.println("quiz details da ** 1a " + quizdt.getQuestionNo());
System.out.println("quiz details da ** 1b " + quizdt.getQuestionDesc());
//step 1 - establish connection to database
db.getConnection();
//step 2 - declare the SQL statement
//dbQuery = "UPDATE QuizDetails SET quizID = ?, setNo = ?, questionNo = ?, questionDesc = ?, option1 = ?, option2 = ?, option3 = ?, option4 =?, correctAnswer = ? WHERE id = ?";
dbQuery = "UPDATE QuizDetails SET questionNo = ?, questionDesc = ?, option1 = ?, option2 = ?, option3 = ?, option4 =?, correctAnswer = ? WHERE id= ?";
pstmt = db.getPreparedStatement(dbQuery);
System.out.println("quiz details da 2 ** " + quizdt.getQuestionNo());
//step 3 - to update record using executeUpdate method
try {
//pstmt.setInt(1, quizdt.getId());
//pstmt.setString(1, quizdt.getQuizID());
//pstmt.setInt(2, quizdt.getSetNo());
pstmt.setInt(1, quizdt.getQuestionNo());
pstmt.setString(2, quizdt.getQuestionDesc());
pstmt.setString(3, quizdt.getOption1());
pstmt.setString(4, quizdt.getOption2());
pstmt.setString(5, quizdt.getOption3());
pstmt.setString(6, quizdt.getOption4());
pstmt.setString(7,quizdt.getCorrectAnswer());
pstmt.setInt(8, quizdt.getId()); //Cannot be hard coded
System.out.println(quizdt.getId());
System.out.println("quiz details da 3 ** " + quizdt.getQuestionNo());
if (pstmt.executeUpdate() == 1)
success = true;
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
}
//step 4 - close connection
db.terminate();
return success;
}
For instance, I would want to update id 1 and it is updated successfully. However, when I want to update id 5 the updated items of id 5 would be then updated to id 1. Anyone encountered this problem while trying to update database?

You should probably provide more information for such question. It is hard to understand what is the context You are making update at. For example if You are using MySQL then You can solve this by fixing the query. Id should be used in where part and not in set part. Something like this should work fine:
UPDATE TABLE `users` SET `name` = 'John' WHERE `id` = 1;

Related

How do I use a couple of multi-dimensional arrays and one-dimentional arrays in a GUI program in Java?

My teacher wants me to create a Java program that functions like a vending machine. She wants it to have multidimensional arrays and one-dimensional arrays. I already created the program but I failed because it doesn't have any array in it. It works perfectly fine but there are no arrays in it that's why I failed. She gave me another chance until tomorrow morning. I am really bad at using arrays, to be honest, and I don't really know how to use them in GUI apps. Thank you so much in advance for your help. Below is my code and the output of the current program I have so far.
import java.awt.EventQueue;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.SystemColor;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.Cursor;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JRadioButton;
public class Finals {
private JFrame frame;
private JTextField itemField;
private JTextField priceField;
private JButton pushButton, button1, button2, button3;
private JRadioButton day1RB, day2RB, day3RB;
private JTextArea resultsTA;
//----Counter Variables for items A1, A2, and A3 for 3 days with 0 as the initial value
int A1d1=0; int A1d2=0; int A1d3=0;
int A2d1=0; int A2d2=0; int A2d3=0;
int A3d1=0; int A3d2=0; int A3d3=0;
//----Amount Variables for items A1, A2, and A3 for 3 days with 0 as the initial value
int A1d1Amount=0; int A1d2Amount=0; int A1d3Amount=0;
int A2d1Amount=0; int A2d2Amount=0; int A2d3Amount=0;
int A3d1Amount=0; int A3d2Amount=0; int A3d3Amount=0;
//----Variables for items B1, B2, and B3 for 3 days with 0 as the initial value
int B1d1=0; int B1d2=0; int B1d3=0;
int B2d1=0; int B2d2=0; int B2d3=0;
int B3d1=0; int B3d2=0; int B3d3=0;
//----Amount Variables for items B1, B2, and B3 for 3 days with 0 as the initial value
int B1d1Amount=0; int B1d2Amount=0; int B1d3Amount=0;
int B2d1Amount=0; int B2d2Amount=0; int B2d3Amount=0;
int B3d1Amount=0; int B3d2Amount=0; int B3d3Amount=0;
//----Variables used for storing total sales for all items for 3 days with 0 as the initial value
double A1total = 0; double A2total=0; double A3total=0;
double B1total = 0; double B2total=0; double B3total=0;
/**
* Launching the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Finals window = new Finals();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Creating the application.
*/
public Finals() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setTitle("Vending Machine");
frame.setResizable(false);
frame.setBounds(100, 100, 914, 334);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel itemsPanel = new JPanel();
itemsPanel.setBackground(SystemColor.activeCaption);
itemsPanel.setBounds(10, 11, 264, 191);
frame.getContentPane().add(itemsPanel);
itemsPanel.setLayout(null);
JLabel a1Label = new JLabel();
a1Label.setBounds(10, 11, 60, 57);
ImageIcon a1Icon = new ImageIcon("cookie.png");
a1Label.setIcon(a1Icon);
itemsPanel.add(a1Label);
JLabel a2Label = new JLabel();
a2Label.setBounds(102, 11, 60, 57);
ImageIcon a2Icon = new ImageIcon("gum.png");
a2Label.setIcon(a2Icon);
itemsPanel.add(a2Label);
JLabel a3Label = new JLabel();
a3Label.setBounds(195, 11, 60, 57);
ImageIcon a3Icon = new ImageIcon("pretzel.png");
a3Label.setIcon(a3Icon);
itemsPanel.add(a3Label);
JLabel b1Label = new JLabel("");
b1Label.setBounds(10, 100, 60, 57);
ImageIcon b1Icon = new ImageIcon("pretzel.png");
b1Label.setIcon(b1Icon);
itemsPanel.add(b1Label);
JLabel b2Label = new JLabel();
b2Label.setBounds(102, 100, 60, 57);
ImageIcon b2Icon = new ImageIcon("cookie.png");
b2Label.setIcon(b2Icon);
itemsPanel.add(b2Label);
JLabel b3Label = new JLabel();
b3Label.setBounds(195, 100, 60, 57);
ImageIcon b3Icon = new ImageIcon("soda.png");
b3Label.setIcon(b3Icon);
itemsPanel.add(b3Label);
JLabel a1lbl = new JLabel("A1");
a1lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
a1lbl.setBounds(27, 63, 25, 26);
itemsPanel.add(a1lbl);
JLabel a2lbl = new JLabel("A2");
a2lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
a2lbl.setBounds(120, 63, 25, 26);
itemsPanel.add(a2lbl);
JLabel a3lbl = new JLabel("A3");
a3lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
a3lbl.setBounds(213, 63, 25, 26);
itemsPanel.add(a3lbl);
JLabel b1lbl = new JLabel("B1");
b1lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
b1lbl.setBounds(27, 154, 25, 26);
itemsPanel.add(b1lbl);
JLabel b2lbl = new JLabel("B2");
b2lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
b2lbl.setBounds(120, 154, 25, 26);
itemsPanel.add(b2lbl);
JLabel b3lbl = new JLabel("B3");
b3lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
b3lbl.setBounds(213, 154, 25, 26);
itemsPanel.add(b3lbl);
pushButton = new JButton("PUSH");
pushButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String selectedItem = itemField.getText();
if(selectedItem.equals("A1") && day1RB.isSelected()) {
A1d1Amount=A1d1Amount+10;
A1d1+=1; A1total = A1d1Amount+A1d2Amount+A1d3Amount;
}
else if(selectedItem.equals("A1") && day2RB.isSelected()) {
A1d2Amount=A1d2Amount+10;
A1d2+=1; A1total = A1d1Amount+A1d2Amount+A1d3Amount;
}else if(selectedItem.equals("A1") && day3RB.isSelected()) {
A1d3Amount=A1d3Amount+10;
A1d3+=1; A1total = A1d1Amount+A1d2Amount+A1d3Amount;
}
else if(selectedItem.equals("A2") && day1RB.isSelected()) {
A2d1Amount=A2d1Amount+20;
A2d1+=1; A2total = A2d1Amount+A2d2Amount+A2d3Amount;
}
else if(selectedItem.equals("A2") && day2RB.isSelected()) {
A2d2Amount=A2d2Amount+20;
A2d2+=1; A2total = A2d1Amount+A2d2Amount+A2d3Amount;
}
else if(selectedItem.equals("A2") && day3RB.isSelected()) {
A2d3Amount=A2d3Amount+20;
A2d3+=1; A2total = A2d1Amount+A2d2Amount+A2d3Amount;
}
else if(selectedItem.equals("A3") && day1RB.isSelected()) {
A3d1Amount=A3d1Amount+30;
A3d1+=1; A3total = A3d1Amount+A3d2Amount+A3d3Amount;
}
else if(selectedItem.equals("A3") && day2RB.isSelected()) {
A3d2Amount=A3d2Amount+30;
A3d2+=1; A3total = A3d1Amount+A3d2Amount+A3d3Amount;
}
else if(selectedItem.equals("A3") && day3RB.isSelected()) {
A3d3Amount=A3d3Amount+30;
A3d3+=1; A3total = A3d1Amount+A3d2Amount+A3d3Amount;
}
else if(selectedItem.equals("B1") && day1RB.isSelected()) {
B1d1Amount=B1d1Amount+15;
B1d1+=1; B1total = B1d1Amount+B1d2Amount+B1d3Amount;
}
else if(selectedItem.equals("B1") && day2RB.isSelected()) {
B1d2Amount=B1d2Amount+15;
B1d2+=1; B1total = B1d1Amount+B1d2Amount+B1d3Amount;
}
else if(selectedItem.equals("B1") && day3RB.isSelected()) {
B1d3Amount=B1d3Amount+15;
B1d3+=1; B1total = B1d1Amount+B1d2Amount+B1d3Amount;
}
else if(selectedItem.equals("B2") && day1RB.isSelected()) {
B2d1Amount=B2d1Amount+25;
B2d1+=1; B2total = B2d1Amount+B2d2Amount+B2d3Amount;
}
else if(selectedItem.equals("B2") && day2RB.isSelected()) {
B2d2Amount=B2d2Amount+25;
B2d2+=1; B2total = B2d1Amount+B2d2Amount+B2d3Amount;
}
else if(selectedItem.equals("B2") && day3RB.isSelected()) {
B2d3Amount=B2d3Amount+25;
B2d3+=1; B2total = B2d1Amount+B2d2Amount+B2d3Amount;
}
else if(selectedItem.equals("B3") && day1RB.isSelected()) {
B3d1Amount=B3d1Amount+35;
B3d1+=1; B3total = B3d1Amount+B3d2Amount+B3d3Amount;
}
else if(selectedItem.equals("B3") && day2RB.isSelected()) {
B3d2Amount=B3d2Amount+35;
B3d2+=1; B3total = B3d1Amount+B3d2Amount+B3d3Amount;
}
else if(selectedItem.equals("B3") && day3RB.isSelected()) {
B3d3Amount=B3d3Amount+35;
B3d3+=1; B3total = B3d1Amount+B3d2Amount+B3d3Amount;
}
double grandTotal = A1total+A2total+A3total+B1total+B2total+B3total;
resultsTA.setText("Item Day1 Day2 Day3 Sales Amount\n\n"
+"A1 "+A1d1+" "+A1d2+" "+A1d3+" ₱"+A1total+"0"
+"\nA2 "+A2d1+" "+A2d2+" "+A2d3+" ₱"+A2total+"0"
+"\nA3 "+A3d1+" "+A3d2+" "+A3d3+" ₱"+A3total+"0"
+"\nB1 "+B1d1+" "+B1d2+" "+B1d3+" ₱"+B1total+"0"
+"\nB2 "+B2d1+" "+B2d2+" "+B2d3+" ₱"+B2total+"0"
+"\nB3 "+B3d1+" "+B3d2+" "+B3d3+" ₱"+B3total+"0"
+"\n\nTotal ₱"+grandTotal+"0"
);
clear();
}
});
pushButton.setEnabled(false);
pushButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
pushButton.setFont(new Font("Tahoma", Font.BOLD, 16));
pushButton.setToolTipText("Press to buy.");
pushButton.setBounds(10, 207, 264, 34);
frame.getContentPane().add(pushButton);
itemField = new JTextField();
itemField.setFont(new Font("Tahoma", Font.BOLD, 16));
itemField.setEditable(false);
itemField.setBounds(293, 11, 218, 34);
frame.getContentPane().add(itemField);
itemField.setColumns(10);
priceField = new JTextField();
priceField.setFont(new Font("Tahoma", Font.BOLD, 16));
priceField.setEditable(false);
priceField.setColumns(10);
priceField.setBounds(293, 56, 218, 34);
frame.getContentPane().add(priceField);
JPanel panel = new JPanel();
panel.setBackground(SystemColor.activeCaption);
panel.setBounds(293, 101, 218, 140);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel label1 = new JLabel("Select a Day of sale first and make");
label1.setFont(new Font("Tahoma", Font.BOLD, 12));
label1.setBounds(2, 2, 216, 14);
panel.add(label1);
JButton aButton = new JButton("A");
aButton.setEnabled(false);
aButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
priceField.setText(null);
pushButton.setEnabled(false);
itemField.setText("A");
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
}
});
aButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
aButton.setFont(new Font("Tahoma", Font.BOLD, 15));
aButton.setBounds(62, 47, 46, 33);
panel.add(aButton);
JButton bButton = new JButton("B");
bButton.setEnabled(false);
bButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
priceField.setText(null);
pushButton.setEnabled(false);
itemField.setText("B");
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
}
});
bButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
bButton.setFont(new Font("Tahoma", Font.BOLD, 15));
bButton.setBounds(118, 47, 46, 33);
panel.add(bButton);
button1 = new JButton("1");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
pushButton.setEnabled(true);
String itemVal = itemField.getText();
itemField.setText(itemVal+"1");
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
String newVal = itemField.getText();
if(newVal.equals("A1")) {
priceField.setText("₱10.00");
}
else {
priceField.setText("₱15.00");
}
}
});
button1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
button1.setEnabled(false);
button1.setFont(new Font("Tahoma", Font.BOLD, 15));
button1.setBounds(10, 91, 46, 33);
panel.add(button1);
button2 = new JButton("2");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
pushButton.setEnabled(true);
String itemVal = itemField.getText();
itemField.setText(itemVal+"2");
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
String newVal = itemField.getText();
if(newVal.equals("A2")) {
priceField.setText("₱20.00");
}
else {
priceField.setText("₱25.00");
}
}
});
button2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
button2.setEnabled(false);
button2.setFont(new Font("Tahoma", Font.BOLD, 15));
button2.setBounds(87, 91, 46, 33);
panel.add(button2);
button3 = new JButton("3");
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
pushButton.setEnabled(true);
String itemVal = itemField.getText();
itemField.setText(itemVal+"3");
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
String newVal = itemField.getText();
if(newVal.equals("A3")) {
priceField.setText("₱30.00");
}
else {
priceField.setText("₱35.00");
}
}
});
button3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
button3.setEnabled(false);
button3.setFont(new Font("Tahoma", Font.BOLD, 15));
button3.setBounds(162, 91, 46, 33);
panel.add(button3);
JLabel label2 = new JLabel("a selection from the items.");
label2.setFont(new Font("Tahoma", Font.BOLD, 12));
label2.setBounds(2, 22, 171, 14);
panel.add(label2);
resultsTA = new JTextArea();
resultsTA.setEditable(false);
resultsTA.setBounds(521, 11, 368, 230);
frame.getContentPane().add(resultsTA);
day1RB = new JRadioButton("Day 1");
day1RB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
aButton.setEnabled(true);
bButton.setEnabled(true);
day2RB.setSelected(false);
day3RB.setSelected(false);
}
});
day1RB.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
day1RB.setFont(new Font("Tahoma", Font.BOLD, 12));
day1RB.setBounds(531, 248, 64, 23);
frame.getContentPane().add(day1RB);
day2RB = new JRadioButton("Day 2");
day2RB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
aButton.setEnabled(true);
bButton.setEnabled(true);
day1RB.setSelected(false);
day3RB.setSelected(false);
}
});
day2RB.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
day2RB.setFont(new Font("Tahoma", Font.BOLD, 12));
day2RB.setBounds(665, 248, 64, 23);
frame.getContentPane().add(day2RB);
day3RB = new JRadioButton("Day 3");
day3RB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
aButton.setEnabled(true);
bButton.setEnabled(true);
day1RB.setSelected(false);
day2RB.setSelected(false);
}
});
day3RB.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
day3RB.setFont(new Font("Tahoma", Font.BOLD, 12));
day3RB.setBounds(797, 249, 64, 23);
frame.getContentPane().add(day3RB);
}
//------Clearing everything after transaction
void clear() {
itemField.setText(null);
priceField.setText(null);
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
pushButton.setEnabled(false);
}
}
output
As a tip to get you started, you could replace your 3 by 3 set of variabls:
int A1d1=0; int A1d2=0; int A1d3=0;
int A2d1=0; int A2d2=0; int A2d3=0;
int A3d1=0; int A3d2=0; int A3d3=0;
With a multi dimensional array with 3 columns and 3 rows:
int[][] num = new int[3][3];
Or like this:
int[][] num = {{0,0,0},
{0,0,0},
{0,0,0}};
Then to replace the first value in the second column and first row we use:
num[1][0] = newValue;
Be careful because the first value of an array is at position num[0][0] not num[1][1]. So for example, when editing/getting a value the last value in an array it would be at position num[2][2], not at num[3][3]

incorrect value from java being inserted into mysql

I have a simple program that takes in info for a car sale and enters it in the MySQL DB, everything inserts 100% properly, except the commission integer. It constantly inserts a constant number, never the 'comm' value I have it set to enter. I have the print statement show the correct value but when i check the DB it's not the correct value. I'm not sure if there's a bug on my end or a JDBC thing?
I've entered a simple value of 1, the print statement reads one but the db will always show a value like 1400.
Image links: https://imgur.com/apuKB0C https://imgur.com/Kijl9yL
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.util.Random;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
public class Sale {
Connection con;
Statement st;
int rs;
ResultSet rs1;
ResultSet rs2;
boolean rs3;
JFrame frame5;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sale window = new Sale();
window.frame5.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void connect() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/project", "root", "Alesana14");
st = con.createStatement();
} catch (Exception ex) {
}
}
/**
* Create the application.
*/
public Sale() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame5 = new JFrame();
frame5.setBounds(100, 100, 834, 543);
frame5.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame5.getContentPane().setLayout(null);
JLabel lblCreateSale = new JLabel("Create Sale");
lblCreateSale.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
lblCreateSale.setBounds(385, 113, 110, 44);
frame5.getContentPane().add(lblCreateSale);
JLabel label_1 = new JLabel("Model:");
label_1.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_1.setBounds(264, 252, 77, 16);
frame5.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Make:");
label_2.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_2.setBounds(264, 214, 77, 16);
frame5.getContentPane().add(label_2);
JLabel label_4 = new JLabel("Price:");
label_4.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_4.setBounds(264, 294, 77, 16);
frame5.getContentPane().add(label_4);
JLabel label_5 = new JLabel("Color:");
label_5.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_5.setBounds(264, 336, 77, 16);
frame5.getContentPane().add(label_5);
textField = new JTextField();
textField.setColumns(10);
textField.setBounds(353, 210, 185, 26);
frame5.getContentPane().add(textField);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(353, 248, 185, 26);
frame5.getContentPane().add(textField_1);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(353, 284, 185, 26);
frame5.getContentPane().add(textField_3);
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String id = textField_6.getText().trim();
String make = textField.getText().trim();
String model = textField_1.getText().trim();
String price = textField_3.getText().trim();
String color = textField_4.getText().trim();
String year = textField_5.getText().trim();
String sql = "UPDATE product SET inventory = inventory-1 WHERE make='" + make + "' and model = '"
+ model + "' and color ='" + color + "' and yearMade=" + year + "";
// executeUpdate for insert,delete, and update
PreparedStatement ps;
ps = Connectivity.getConnection().prepareStatement(sql);
rs = ps.executeUpdate();
String sql1 = "UPDATE employee SET commission = commission + (commissionRate*"+price+") WHERE id = "+id+"";
ps = Connectivity.getConnection().prepareStatement(sql1);
rs = ps.executeUpdate();
//inserts into sales
Random rand = new Random();
int random =rand.nextInt(999999);
String sql2 = "SELECT id FROM product WHERE make = '"+make+"' and model = '"+model+"' and color = '"+color+"' and yearMade = '"+year+"'";
st = Connectivity.getConnection().createStatement();
rs2 = st.executeQuery(sql2);
while(rs2.next()) {
int totalPrice = Integer.parseInt(price);
Double comm = totalPrice * .035;
int prodID = rs2.getInt("id");
String sql3 = "INSERT INTO sales VALUES('"+random+"','"+id+"','"+prodID+"','"+1+"','"+totalPrice+"',"+comm+")";
ps = Connectivity.getConnection().prepareStatement(sql3);
rs = ps.executeUpdate();
System.out.println(totalPrice);
System.out.println(comm);
System.out.println(ps);
}
JOptionPane.showMessageDialog(null, "Items Sold!");
}
catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnEnter.setBounds(423, 407, 130, 29);
frame5.getContentPane().add(btnEnter);
JButton button_1 = new JButton("Return to menu");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu men = new Menu();
men.frame2.setVisible(true);
frame5.setVisible(false);
}
});
button_1.setBounds(266, 407, 145, 29);
frame5.getContentPane().add(button_1);
textField_4 = new JTextField();
textField_4.setColumns(10);
textField_4.setBounds(353, 326, 185, 26);
frame5.getContentPane().add(textField_4);
JLabel label_6 = new JLabel("Year:");
label_6.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_6.setBounds(264, 374, 77, 16);
frame5.getContentPane().add(label_6);
textField_5 = new JTextField();
textField_5.setColumns(10);
textField_5.setBounds(353, 364, 185, 26);
frame5.getContentPane().add(textField_5);
JLabel lblEmployeeId = new JLabel("Employee ID:\n\n");
lblEmployeeId.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
lblEmployeeId.setBounds(245, 172, 121, 16);
frame5.getContentPane().add(lblEmployeeId);
textField_6 = new JTextField();
textField_6.setColumns(10);
textField_6.setBounds(353, 169, 185, 26);
frame5.getContentPane().add(textField_6);
JLabel imgLabel = new JLabel(new ImageIcon("/Users/jonathonmoreno/Desktop/Project/src/resize.png"));
imgLabel.setBounds(-11, 0, 845, 521);
frame5.getContentPane().add(imgLabel);
}
}

Jcombobox not selecting item

Im trying to insert the Jcombobox value into my sqlite database but whenever I run the program, it only inserts '9' in to my database. Please advise. I am trying to import the integer that the user picks into my sqlite database. For some reason, even with the action listener, the default value, 9, is still being inputed into the table and im not sure why. Here is the full code, not including the connection and the Jtable.
public class create extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
create frame = new create();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connect = null;
private JTextField textField_2;
String uniqueString = UUID.randomUUID().toString();
private JTextField textField_3;
/**
* Create the frame.
*/
public create() {
connect = connection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBackground(new Color(204, 204, 204));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblStudentName = new JLabel("Student ID:");
lblStudentName.setBounds(96, 69, 72, 16);
contentPane.add(lblStudentName);
textField = new JTextField();
textField.setBounds(173, 64, 216, 26);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblGrade = new JLabel("Grade:");
lblGrade.setBounds(125, 107, 47, 16);
contentPane.add(lblGrade);
JComboBox comboBox = new JComboBox();
comboBox.addItem(9);
comboBox.addItem(10);
comboBox.addItem(11);
comboBox.addItem(12);
comboBox.setBounds(173, 102, 72, 29);
contentPane.add(comboBox);
comboBox.setSelectedItem(9);
comboBox.addActionListener(comboBox);
int selectedNumber = (int)comboBox.getSelectedItem();
JLabel lblInputBookOver = new JLabel("Teacher:");
lblInputBookOver.setBounds(111, 146, 61, 21);
contentPane.add(lblInputBookOver);
textField_1 = new JTextField();
textField_1.setBounds(173, 143, 216, 26);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton button = new JButton("<");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int count = 0; count <= 0; count++) {
//dispose();
options sc = new options();
sc.setVisible(true);
}
}
});
button.setBounds(6, 6, 30, 29);
contentPane.add(button);
JLabel lblStudentname = new JLabel("Student Name:");
lblStudentname.setBounds(74, 31, 99, 16);
contentPane.add(lblStudentname);
textField_2 = new JTextField();
textField_2.setBounds(173, 26, 216, 26);
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(125, 180, 42, 26);
contentPane.add(lblEmail);
textField_3 = new JTextField();
textField_3.setBounds(173, 180, 216, 26);
contentPane.add(textField_3);
textField_3.setColumns(10);
JButton btnCheckout = new JButton("Checkout");
btnCheckout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String uniqueString = UUID.randomUUID().toString().replace("-", "");
try {
String query = "insert into data ('Name', 'Student ID', 'Teacher', 'Grade', 'Email', 'Ebook') values (?,?,?,?,?,?)";
PreparedStatement pst = connect.prepareStatement(query);
pst.setString(1,textField_2.getText() );
pst.setString(2,textField.getText() );
pst.setString(3,textField_1.getText() );
pst.setInt(4, selectedNumber);
pst.setString(5,textField_3.getText() );
pst.setString(6, uniqueString);
for (int count = 0; count <= 0; count++) {
//dispose();
confirm sc = new confirm();
sc.setVisible(true);
count = 0;
}
pst.execute();
pst.close();
}
catch (Exception w){
w.printStackTrace();
}
}
});
btnCheckout.setBounds(173, 218, 117, 29);
contentPane.add(btnCheckout);
}
}
It inserts 9 to your database because the selected item is always 9, and this because you add it first to your combobox. In order to insert the selected value, you will have to use an ActionListener. Then you can take user's selection and do whatever you want.
An example of its usage:
import java.awt.FlowLayout;
import java.io.FileNotFoundException;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class ComboBox extends JFrame {
public ComboBox() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
getContentPane().setLayout(new FlowLayout());
Integer[] numbers = { 4, 5, 8, 123, 42, 634 };
JComboBox<Integer> comboBox = new JComboBox<>(numbers);
comboBox.setSelectedItem(42); // The initial selection is 42.
comboBox.addActionListener(e -> {
int selectedNumber = (int) comboBox.getSelectedItem();
System.out.println("Selected number: " + selectedNumber);
// Do whatever with selected number
});
add(comboBox);
}
public static void main(String[] args) throws FileNotFoundException {
SwingUtilities.invokeLater(() -> new ComboBox().setVisible(true));
}
}

Java - Call Method from sub class By pressing a JButton in the base class

Can I call a method from an extended class by pressing a JButton?
I know how to display messages etc when pressing a JButton, but I want to know if it is possible to do this?
I want to call methods from Activate_and_Deactivate class to use as action performed by pressing radiobuttons ON and OF. I can directly place the statements in the actionevent argument but the teacher said I have to use inheritance atleast for something.
this is my code.
package Calculators;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.Button;
import java.awt.Color;
import javax.swing.JLabel;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.JRadioButton;
public class UIFrame {
Activate_and_Deactivate act = new Activate_and_Deactivate();
JButton button0 = new JButton("0");
JButton button2 = new JButton("2");
JButton button1 = new JButton("1");
JButton button3 = new JButton("3");
JButton button4 = new JButton("4");
JButton button5 = new JButton("5");
JButton button6 = new JButton("6");
JButton button7 = new JButton("7");
JButton button8 = new JButton("8");
JButton button9 = new JButton("9");
JButton button_Div = new JButton("/");
JButton button_C = new JButton("C");
JButton button_Mul = new JButton("*");
JButton button_Add = new JButton("+");
JButton button_Sub = new JButton("-");
JButton button_Dot = new JButton(".");
JButton button_rec = new JButton("1/x");
JButton button_Sqr = new JButton("\u221A");
JButton button_neg = new JButton("±");
JButton button_per = new JButton("%");
JButton button_equal = new JButton("=");
JButton button_undo = new JButton("\u2190");
JButton btnExit = new JButton("exit");
JRadioButton rdbtnOn = new JRadioButton("On");
JRadioButton rdbtnOff = new JRadioButton("Off");
private JFrame frmCalculator;
private JTextField screen;
private JTextField value1;
private JTextField value2;
private JLabel operation;
double fNumber = 0;
double sNumber = 0;
double result = 0;
String ope;
String answer;
public static void main(String[] args) {
try
{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); //Motif, and Windows packages that it requires are shipped with the Java SDK this way
}
catch(Exception e){}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIFrame window = new UIFrame();
window.frmCalculator.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UIFrame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmCalculator = new JFrame();
frmCalculator.setTitle("Java calculator ver 3.1.6 by Muhammad Haroon");
frmCalculator.getContentPane().setBackground(new Color(0, 0, 0));
frmCalculator.getContentPane().setForeground(Color.DARK_GRAY);
frmCalculator.setBounds(100, 100, 326, 422);
frmCalculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmCalculator.getContentPane().setLayout(null);
value1 = new JTextField();
value1.setForeground(Color.DARK_GRAY);
value1.setFont(new Font("Tahoma", Font.PLAIN, 19));
value1.setHorizontalAlignment(SwingConstants.RIGHT);
value1.setBorder(null);
value1.setBounds(151, 52, 141, 31);
frmCalculator.getContentPane().add(value1);
value1.setColumns(10);
value2 = new JTextField();
value2.setFont(new Font("Tahoma", Font.PLAIN, 24));
value2.setHorizontalAlignment(SwingConstants.RIGHT);
value2.setBorder(null);
value2.setBounds(71, 90, 218, 37);
frmCalculator.getContentPane().add(value2);
value2.setColumns(10);
operation = new JLabel("");
operation.setForeground(new Color(144, 238, 144));
operation.setHorizontalAlignment(SwingConstants.LEFT);
operation.setFont(new Font("Tahoma", Font.PLAIN, 20));
operation.setBounds(20, 97, 50, 31);
frmCalculator.getContentPane().add(operation);
screen = new JTextField();
screen.setBorder(new CompoundBorder(new EtchedBorder(EtchedBorder.RAISED, null, null), new EtchedBorder(EtchedBorder.LOWERED, null, null)));
screen.setEditable(false);
screen.setHorizontalAlignment(SwingConstants.RIGHT);
screen.setBounds(10, 48, 289, 82);
frmCalculator.getContentPane().add(screen);
screen.setColumns(10);
rdbtnOn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
act.activate();
}
});
rdbtnOn.setFont(new Font("Cambria Math", Font.PLAIN, 12));
rdbtnOn.setForeground(new Color(255, 255, 255));
rdbtnOn.setBounds(11, 18, 38, 23);
frmCalculator.getContentPane().add(rdbtnOn);
rdbtnOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
act.deactivate();
}
});
rdbtnOff.setFont(new Font("Cambria Math", Font.PLAIN, 12));
rdbtnOff.setForeground(new Color(255, 255, 255));
rdbtnOff.setBounds(51, 18, 38, 23);
frmCalculator.getContentPane().add(rdbtnOff);
button0.setBackground(new Color(135, 206, 250));
button0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button0.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button0.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button0.setBounds(11, 306, 110, 31);
frmCalculator.getContentPane().add(button0);
button2.setBackground(new Color(135, 206, 250));
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button2.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button1.setBackground(new Color(135, 206, 250));
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button1.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button1.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button1.setBounds(11, 264, 50, 31);
frmCalculator.getContentPane().add(button1);
button2.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button2.setBounds(71, 264, 50, 31);
frmCalculator.getContentPane().add(button2);
button3.setBackground(new Color(135, 206, 250));
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button3.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button3.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button3.setBounds(131, 264, 50, 31);
frmCalculator.getContentPane().add(button3);
button4.setBackground(new Color(135, 206, 250));
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button4.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button4.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button4.setBounds(11, 222, 50, 31);
frmCalculator.getContentPane().add(button4);
button5.setBackground(new Color(135, 206, 250));
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button5.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button5.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button5.setBounds(71, 222, 50, 31);
frmCalculator.getContentPane().add(button5);
button6.setBackground(new Color(135, 206, 250));
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button6.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button6.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button6.setBounds(131, 222, 50, 31);
frmCalculator.getContentPane().add(button6);
button7.setBackground(new Color(135, 206, 250));
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String num = value2.getText() + button7.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button7.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button7.setBounds(11, 180, 50, 31);
frmCalculator.getContentPane().add(button7);
button8.setBackground(new Color(135, 206, 250));
button8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button8.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button8.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button8.setBounds(71, 180, 50, 31);
frmCalculator.getContentPane().add(button8);
button9.setBackground(new Color(135, 206, 250));
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button9.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button9.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button9.setBounds(131, 180, 50, 31);
frmCalculator.getContentPane().add(button9);
button_Div.setBackground(new Color(192, 192, 192));
button_Div.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value2.getText());
operation.setText("/");
value2.setText(null);
}
});
button_C.setBackground(new Color(60, 179, 113));
button_C.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value2.setText(null);
value1.setText(null);
operation.setText(null);
}
});
button_C.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_C.setBounds(71, 138, 50, 31);
frmCalculator.getContentPane().add(button_C);
button_Div.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_Div.setBounds(191, 180, 50, 31);
frmCalculator.getContentPane().add(button_Div);
button_Mul.setBackground(new Color(192, 192, 192));
button_Mul.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value2.getText());
operation.setText("*");
value2.setText(null);
}
});
button_Mul.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_Mul.setBounds(191, 222, 50, 31);
frmCalculator.getContentPane().add(button_Mul);
button_Add.setBackground(new Color(192, 192, 192));
button_Add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value2.getText());
operation.setText("+");
ope = "+";
value2.setText(null);
}
});
button_Add.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_Add.setBounds(191, 306, 50, 31);
frmCalculator.getContentPane().add(button_Add);
button_Sub.setBackground(new Color(192, 192, 192));
button_Sub.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value1.setText(value2.getText());
operation.setText("-");
value2.setText(null);
}
});
button_Sub.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_Sub.setBounds(191, 264, 50, 31);
frmCalculator.getContentPane().add(button_Sub);
button_Dot.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = value2.getText() + button_Dot.getText(); //value.setText(value.getText()+Button)
value2.setText(num);
}
});
button_Dot.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_Dot.setBounds(131, 306, 50, 31);
frmCalculator.getContentPane().add(button_Dot);
button_rec.setBackground(new Color(192, 192, 192));
button_rec.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double ops1 = Double.parseDouble(String.valueOf(value2.getText()));
double ops2 = Double.parseDouble(String.valueOf(value2.getText()));
ops1 = 1/ops2;
value2.setText(String.valueOf(ops1));
value1.setText("reciproc("+String.valueOf(ops2)+")");
}
});
//ALT+251
button_Sqr.setBackground(new Color(192, 192, 192));
button_Sqr.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double ops = Double.parseDouble(String.valueOf(value2.getText()));
ops = Math.sqrt(ops);
value2.setText(String.valueOf(ops));
value1.setText("sqrt("+String.valueOf(ops*ops)+")");
}
});
button_Sqr.setFont(new Font("Cambria Math", Font.PLAIN, 13));
button_Sqr.setBounds(131, 138, 50, 31);
frmCalculator.getContentPane().add(button_Sqr);
button_rec.setFont(new Font("Cambria Math", Font.PLAIN, 11));
button_rec.setBounds(249, 222, 50, 31);
frmCalculator.getContentPane().add(button_rec);
//ALT+0177
button_neg.setBackground(new Color(192, 192, 192));
button_neg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double ops = Double.parseDouble(String.valueOf(value2.getText()));
ops = ops * (-1);
value2.setText(String.valueOf(ops));
value1.setText("negate("+String.valueOf(ops*-1)+")");
}
});
button_neg.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_neg.setBounds(191, 138, 50, 31);
frmCalculator.getContentPane().add(button_neg);
button_per.setBackground(new Color(192, 192, 192));
button_per.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double ops = Double.parseDouble(String.valueOf(value2.getText()));
ops = ops * (100);
value2.setText(String.valueOf(ops));
value1.setText(String.valueOf(ops));
}
});
button_per.setBounds(249, 180, 50, 31);
frmCalculator.getContentPane().add(button_per);
button_equal.setBackground(new Color(60, 179, 113));
button_equal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fNumber = Double.parseDouble(value1.getText());
sNumber = Double.parseDouble(value2.getText());
if(operation.getText().equals("+"))
{
result = fNumber + sNumber ;
value1.setText(null);
value2.setText(String.valueOf(result));
}
else if(operation.getText().equals("-"))
{
result = fNumber - sNumber ;
value1.setText(null);
value2.setText(String.valueOf(result));
}
else if(operation.getText().equals("*"))
{
result = fNumber * sNumber ;
value1.setText(null);
value2.setText(String.valueOf(result));
}
else if(operation.getText().equals("/"))
{
result = fNumber / sNumber ;
value1.setText(null);
value2.setText(String.valueOf(result));
}
}
});
//ALT+8592
button_undo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String bkspace = null;
if(value2.getText().length() > 0)
{
StringBuilder strB = new StringBuilder(value2.getText());
strB.deleteCharAt(value2.getText().length() - 1);
bkspace = strB.toString();
value2.setText(bkspace);
}
}
});
button_undo.setFont(new Font("Cambria Math", Font.PLAIN, 19));
button_undo.setBounds(10, 138, 50, 31);
frmCalculator.getContentPane().add(button_undo);
button_equal.setFont(new Font("Cambria Math", Font.PLAIN, 18));
button_equal.setBounds(249, 264, 50, 73);
frmCalculator.getContentPane().add(button_equal);
btnExit.setBackground(new Color(255, 99, 71));
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnExit.setFont(new Font("Cambria Math", Font.PLAIN, 12));
btnExit.setBounds(11, 348, 51, 23);
frmCalculator.getContentPane().add(btnExit);
}
/**
* #return the activate_and_Deactivate
*/
public Object getActivate_and_Deactivate() {
return Activate_and_Deactivate;
}
/**
* #param activate_and_Deactivate the activate_and_Deactivate to set
*/
public void setActivate_and_Deactivate(Object activate_and_Deactivate) {
Activate_and_Deactivate = activate_and_Deactivate;
}
}
package Calculators;
import javax.swing.JButton;
import javax.swing.JRadioButton;
public class Activate_and_Deactivate extends UIFrame
{
public void activate()
{
button0.setEnabled(true);
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
button4.setEnabled(true);
button5.setEnabled(true);
button6.setEnabled(true);
button7.setEnabled(true);
button8.setEnabled(true);
button9.setEnabled(true);
button_Div .setEnabled(true);
button_C .setEnabled(true);
button_Mul.setEnabled(true);
button_Add.setEnabled(true);
button_Sub.setEnabled(true);
button_Dot.setEnabled(true);
button_rec.setEnabled(true);
button_Sqr.setEnabled(true);
button_neg.setEnabled(true);
button_per .setEnabled(true);
button_equal.setEnabled(true);
button_undo .setEnabled(true);
btnExit .setEnabled(true);
rdbtnOff.setEnabled(true);
rdbtnOn.setEnabled(false);
}
public void deactivate()
{
button0.setEnabled(false);
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
button4.setEnabled(false);
button5.setEnabled(false);
button6.setEnabled(false);
button7.setEnabled(false);
button8.setEnabled(false);
button9.setEnabled(false);
button_Div .setEnabled(false);
button_C .setEnabled(false);
button_Mul.setEnabled(false);
button_Add.setEnabled(false);
button_Sub.setEnabled(false);
button_Dot.setEnabled(false);
button_rec.setEnabled(false);
button_Sqr.setEnabled(false);
button_neg.setEnabled(false);
button_per .setEnabled(false);
button_equal.setEnabled(false);
button_undo .setEnabled(false);
btnExit .setEnabled(false);
rdbtnOn.setEnabled(true);
rdbtnOff.setEnabled(false);
}
}
Its not working. Can someone help me.
Many thanks.
As far as I know, you can not use your base class as an instance of your derived class.
However, you can store an instance of the derived class in your base class and then cast it back to the derived class when you need to. See the ActionListener on the button for an example
Base
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class SimpleClass extends JFrame {
public SimpleClass(String title) {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout());
setUp();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public SimpleClass() {
}
public void setUp() {
JPanel panel = new JPanel();
ExtendedClass e = new ExtendedClass();
SimpleClass s = new ExtendedClass();
SimpleClass thisInstance = this;
JButton button = new JButton("Press Me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(e instanceof ExtendedClass);
e.printLn();
System.out.println(s instanceof ExtendedClass);
((ExtendedClass)s).printLn();
System.out.println(thisInstance instanceof ExtendedClass);
//Returns an exception as it is not an instance of ExtendedClass
((ExtendedClass)thisInstance).printLn();
}
});
panel.add(button);
getContentPane().add(panel);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new SimpleClass("Title"));
}
}
Extended
#SuppressWarnings("serial")
public class ExtendedClass extends SimpleClass {
public void printLn() {
System.out.println("Printed A Line To The Console :)");
}
}

error : "java.sql.SQLException: No value specified for parameter 1 "

public class VerEstoque extends JFrame {
Connection conexao;
PreparedStatement pst;
ResultSet rs;
public void Adicionar()
{
String sql = "INSERT INTO Produtos (Nome, Marca, Loja, Estoque ,ValordeVenda) VALUES (?,?,?,?,?)";
try
{
pst = conexao.prepareStatement(sql);
pst.setString(1,textNome.getText());
pst.setString(2,textMarca.getText());
pst.setString(3,textLoja.getText());
pst.setString(4,textEstoque.getText());
pst.setString(5,textValordeVenda.getText());
pst.execute();
JOptionPane.showMessageDialog(null,"Produto adicionado com sucesso!", "Cadastrado com Sucesso", JOptionPane.INFORMATION_MESSAGE);
listarProdutos();
}
catch(SQLException error)
{
JOptionPane.showMessageDialog(null,"Erro ao adicionar o produto!");
}
}
public void listarProdutos(){
String sql = "Select *from Produtos";
try{
pst = conexao.prepareStatement(sql);
rs = pst.executeQuery();
tblProdutos.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(SQLException error){
JOptionPane.showMessageDialog(null, error);
}
}
public void buscarProdutos(){
String sql = "Select *from Produtos where Nome like ?";
try{
pst = conexao.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(1,textBusca.getText()+"%");
tblProdutos.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(SQLException error){
JOptionPane.showMessageDialog(null, error);
}
}
private JPanel contentPane;
private JTextField textNome;
private JTextField textMarca;
private JTextField textLoja;
private JTextField textEstoque;
private JTextField textValordeVenda;
protected AbstractButton rdbtnRemover;
private JTable tblProdutos;
private JTextField textBusca;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VerEstoque frame = new VerEstoque();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public VerEstoque() throws ClassNotFoundException {
conexao = BancoDeDados.bancodedados();
setBackground(new Color(238, 238, 238));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 697, 514);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textNome = new JTextField();
textNome.setHorizontalAlignment(SwingConstants.CENTER);
textNome.setBounds(289, 68, 134, 28);
contentPane.add(textNome);
textNome.setColumns(10);
textMarca = new JTextField();
textMarca.setHorizontalAlignment(SwingConstants.CENTER);
textMarca.setBounds(289, 96, 134, 28);
contentPane.add(textMarca);
textMarca.setColumns(10);
textLoja = new JTextField();
textLoja.setHorizontalAlignment(SwingConstants.CENTER);
textLoja.setBounds(289, 125, 134, 28);
contentPane.add(textLoja);
textLoja.setColumns(10);
textEstoque = new JTextField();
textEstoque.setHorizontalAlignment(SwingConstants.CENTER);
textEstoque.setBounds(289, 152, 134, 28);
contentPane.add(textEstoque);
textEstoque.setColumns(10);
textValordeVenda = new JTextField();
textValordeVenda.setHorizontalAlignment(SwingConstants.CENTER);
textValordeVenda.setBounds(289, 181, 134, 28);
contentPane.add(textValordeVenda);
textValordeVenda.setColumns(10);
JButton btnAdicionar = new JButton("Adicionar!");
btnAdicionar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Adicionar();
}
});
btnAdicionar.setBounds(507, 69, 117, 29);
contentPane.add(btnAdicionar);
JButton btnTabela = new JButton("Ver tabela completa de estoque!");
btnTabela.setToolTipText("");
btnTabela.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
listarProdutos();
}
});
btnTabela.setBounds(140, 421, 441, 45);
contentPane.add(btnTabela);
JButton btnBuscar = new JButton("Buscar!");
btnBuscar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buscarProdutos();
}
});
btnBuscar.setBounds(16, 126, 117, 29);
contentPane.add(btnBuscar);
JTextPane txtpnSelecioneAOpo = new JTextPane();
txtpnSelecioneAOpo.setFont(new Font("Comic Sans MS", Font.BOLD | Font.ITALIC, 15));
txtpnSelecioneAOpo.setBackground(SystemColor.window);
txtpnSelecioneAOpo.setText("Selecione a opção que deseja fazer :");
txtpnSelecioneAOpo.setBounds(186, 6, 284, 23);
contentPane.add(txtpnSelecioneAOpo);
JLabel lblNome = new JLabel("Nome :");
lblNome.setBounds(177, 74, 61, 16);
contentPane.add(lblNome);
JLabel lblMarca = new JLabel("Marca :");
lblMarca.setBounds(177, 102, 61, 16);
contentPane.add(lblMarca);
JLabel lblLoja = new JLabel("Loja :");
lblLoja.setBounds(178, 131, 43, 16);
contentPane.add(lblLoja);
JLabel lblEstoque = new JLabel("Estoque :");
lblEstoque.setBounds(177, 158, 61, 16);
contentPane.add(lblEstoque);
JLabel lblValorDeVenda = new JLabel("Valor de Venda :");
lblValorDeVenda.setBounds(177, 187, 108, 16);
contentPane.add(lblValorDeVenda);
JButton btnRemover = new JButton("Remover!");
btnRemover.setBounds(507, 182, 117, 29);
contentPane.add(btnRemover);
JRadioButton rdbtnBuscar = new JRadioButton("Buscar");
rdbtnBuscar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textEstoque.setEditable(false);
textValordeVenda.setEditable(false);
textLoja.setEditable(false);
textMarca.setEditable(false);
}
});
rdbtnBuscar.setBounds(140, 34, 98, 23);
contentPane.add(rdbtnBuscar);
JRadioButton rdbtnAdicionar = new JRadioButton("Adicionar");
rdbtnAdicionar.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
textNome.setEditable(true);
textEstoque.setEditable(true);
textValordeVenda.setEditable(true);
textLoja.setEditable(true);
textMarca.setEditable(true);
}
});
rdbtnAdicionar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textNome.setEditable(true);
textEstoque.setEditable(true);
textValordeVenda.setEditable(true);
textLoja.setEditable(true);
textMarca.setEditable(true);
}
});
rdbtnAdicionar.setBounds(279, 34, 98, 23);
contentPane.add(rdbtnAdicionar);
JRadioButton rdbtnRemover = new JRadioButton("Remover");
rdbtnAdicionar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textNome.setEditable(true);
textEstoque.setEditable(true);
textValordeVenda.setEditable(false);
textLoja.setEditable(false);
textMarca.setEditable(false);
}
});
rdbtnRemover.setBounds(440, 34, 141, 23);
contentPane.add(rdbtnRemover);
JButton btnCancelar = new JButton("Cancelar!");
btnCancelar.setBounds(417, 126, 98, 28);
contentPane.add(btnCancelar);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(29, 251, 643, 170);
contentPane.add(scrollPane);
tblProdutos = new JTable();
scrollPane.setViewportView(tblProdutos);
tblProdutos.setToolTipText("");
JLabel pesquisaproduto = new JLabel("Nome do Produto para Busca : ");
pesquisaproduto.setBounds(29, 228, 226, 16);
contentPane.add(pesquisaproduto);
textBusca = new JTextField();
textBusca.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
buscarProdutos();
}
});
textBusca.setBounds(244, 222, 214, 28);
contentPane.add(textBusca);
textBusca.setColumns(10);
}
}
When I write some text on textBusca and then select buscarProdutos button to do a search, I receive this error:
java.sql.SQLException: No value specified for parameter 1.
You execute the query before setting the first parameter :
pst = conexao.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(1,textBusca.getText()+"%");
change to
pst = conexao.prepareStatement(sql);
pst.setString(1,textBusca.getText()+"%");
rs = pst.executeQuery();

Categories

Resources