Loading data from a sqlite database in Java? - java

I am new to the world of Java and sqlite database. I was trying out some codes about loading data from a database into a tabular view using java in eclipse. Now, here is the thing, when my data loads from the database, i want to add an extra column which contains a checkbox(unchecked). Can someone suggest me how do i implement it? Please note that when i run the code, it works absolutely fine and shows no error....I am able to see all the records in my table without any error. Just want an unchecked checkbox to be added to each row so that when i click on it, i can do something. Thats my goal..
Here is what i tried so far.. I have two classes namely:-
1. sqliteConnection.java(which is for connection )
2. employeeinfo.java class which is for loading the data from the database into a table and other functionalities.
import java.sql.*;
import javax.swing.*;
public class sqliteConnection {
Connection conn = null;
public static Connection dbConnector()
{
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\user\\Downloads\\Documents\\MyJavaProjects\\Phone\\Employee.sqlite");
JOptionPane.showMessageDialog(null, "Connection Succesful");
return conn;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
public sqliteConnection() {
// TODO Auto-generated constructor stub
}
}
employeeinfo.java --
import java.awt.BorderLayout;
public class employeeinfo extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
employeeinfo frame = new employeeinfo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connection = null;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
public employeeinfo() {
connection = sqliteConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 842, 457);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblJframe = new JLabel("Jframe2");
lblJframe.setBounds(47, 37, 46, 14);
contentPane.add(lblJframe);
JButton btnLoad = new JButton("Load");
btnLoad.addActionListener(new ActionListener() {
PreparedStatement pat;
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select eid,Name,Surname,Age from EmployeeInfo ";
pat = connection.prepareStatement(query);
ResultSet rs = pat.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e)
{
}
}
});
btnLoad.setBounds(104, 33, 89, 23);
contentPane.add(btnLoad);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(429, 48, 370, 232);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JLabel lblName = new JLabel("EID");
lblName.setBounds(10, 98, 46, 21);
contentPane.add(lblName);
textField = new JTextField();
textField.setBounds(107, 99, 126, 20);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblName_1 = new JLabel("Name");
lblName_1.setBounds(10, 154, 46, 14);
contentPane.add(lblName_1);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(107, 151, 126, 20);
contentPane.add(textField_1);
JLabel lblSurname = new JLabel("Surname");
lblSurname.setBounds(10, 204, 46, 14);
contentPane.add(lblSurname);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(104, 201, 126, 20);
contentPane.add(textField_2);
JLabel lblAge = new JLabel("Age");
lblAge.setBounds(10, 278, 46, 14);
contentPane.add(lblAge);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(104, 275, 126, 20);
contentPane.add(textField_3);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
PreparedStatement pat;
try {
String query = "insert into EmployeeInfo(EID,name,surname,age) values(?,?,?,?)";
pat = connection.prepareStatement(query);
pat.setString(1, textField.getText());
pat.setString(2, textField_1.getText());
pat.setString(3, textField_2.getText());
pat.setString(4, textField_3.getText());
pat.execute();
JOptionPane.showMessageDialog(null, "Data Saved successfully");
pat.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
btnSave.setBounds(72, 349, 89, 23);
contentPane.add(btnSave);
JButton btnClear = new JButton("Clear");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
textField_1.setText("");
textField_2.setText("");
textField_3.setText("");
}
});
btnClear.setBounds(206, 349, 89, 23);
contentPane.add(btnClear);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
String query="Update EmployeeInfo set EID='"+textField.getText()+"',Name='"+textField_1.getText()+"'"
+",Surname='"+textField_2.getText()+"',Age='"+textField_3.getText()+"'where EID='"+textField.getText()+"'";
// JOptionPane.showMessageDialog(null, query);
PreparedStatement pst=connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Data Saved successfully");
pst.close();
}
catch(Exception f)
{
f.printStackTrace();
}
}
});
btnUpdate.setBounds(323, 349, 89, 23);
contentPane.add(btnUpdate);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
String query="delete from EmployeeInfo where EID='"+textField.getText()+"'";
// JOptionPane.showMessageDialog(null, query);
PreparedStatement pst=connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Data deleted successfully");
pst.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
btnDelete.setBounds(453, 349, 89, 23);
contentPane.add(btnDelete);
}
}

My suggestion is you first go through this article, it's a very simpler way of loading data from ResultSet to DefaultTableModel. After this you have to make some small changes like, you have to add another column heading to the Vector of columnNames and add a column for check boxes. Then when you process each row from the ResultSet you need to add a Boolean value to the row Vector with a checkbox .

Related

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));
}
}

How to update row selected by id column?

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;

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();

Runnable jar connects to sqlite but exe of the same doesn't

I have created a runnable jar file for a login page. The folder where the runnable jar is saved also contains a folder named "lib" which contains files for images (used for icons and stuff) and an sqlite database file (which contains usernames and passwords).
When I execute the runnable jar and click on the login button after entering the username and password, it successfully executes. But when I convert the same jar file to exe and run it, the images from lib folder get loaded, but nothing happens when I click the login button. It seems as if the exe file is not connecting to the sqlite database in the "lib" folder.
Following is the code:
package db;
import javax.swing.*;
public class One extends JFrame {
private JButton btn_login = new JButton("LOGIN");
private JPanel panel = new JPanel();
private JTextField tf_user;
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs= null;
private JPasswordField tf_pass;
public static void main(String[] args) {
One frameTabel = new One();
}
One(){
super("LOGIN PAGE");
setTitle("NETWORK TRACKER - LOGIN");
setBackground(new Color(70, 130, 180));
btn_login.setFont(new Font("Tahoma", Font.PLAIN, 8));
btn_login.setBackground(new Color(102, 205, 170));
btn_login.setForeground(Color.WHITE);
btn_login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:lib/login.sqlite");
String sql = "SELECT * from table12 where Username=? and Password=?";
pst = conn.prepareStatement(sql);
pst.setString(1, tf_user.getText());
pst.setString(2, tf_pass.getText());
rs = pst.executeQuery();
if(rs.next()){
rs.close();
pst.close();
setVisible(false);
Display dp = new Display();
dp.setVisible(true);
dp.setSize(300, 300);
} else{
JOptionPane.showMessageDialog(null, "Username or Password is not correct");
}
} catch (Exception e){
System.out.println("Error: "+e);
} finally{
try{
rs.close();
pst.close();
} catch (Exception e){
}
}
}
});
btn_login.setBounds(342,153,58,20);
panel.setBackground(new Color(112, 128, 144));
panel.add(btn_login);
setupLog();
getContentPane().add(panel);
JLabel lbl_title = new JLabel("NETWORK TRACKER LOGIN PAGE ");
lbl_title.setBackground(new Color(47, 79, 79));
lbl_title.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_title.setForeground(Color.LIGHT_GRAY);
lbl_title.setFont(new Font("HelveticaNeue", Font.PLAIN, 16));
lbl_title.setBounds(0, 252, 457, 23);
panel.add(lbl_title);
JLabel lbl_user = new JLabel("USERNAME");
lbl_user.setFont(new Font("HelveticaNeue", Font.PLAIN, 12));
lbl_user.setForeground(new Color(255, 250, 250));
lbl_user.setBounds(263, 93, 69, 14);
panel.add(lbl_user);
tf_user = new JTextField();
tf_user.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
tf_user.setBounds(342, 90, 105, 22);
panel.add(tf_user);
tf_user.setColumns(10);
JLabel lbl_pass = new JLabel("PASSWORD");
lbl_pass.setFont(new Font("HelveticaNeue", Font.PLAIN, 12));
lbl_pass.setForeground(new Color(255, 250, 250));
lbl_pass.setBounds(263, 129, 69, 14);
panel.add(lbl_pass);
tf_pass = new JPasswordField();
tf_pass.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
tf_pass.setBounds(342, 123, 105, 20);
panel.add(tf_pass);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon("lib/login.png"));
label.setBounds(0, 11, 236, 240);
panel.add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void setupLog(){
setSize(473,313);
setLocation(500,280);
panel.setLayout (null);
}
}

How do I insert Java variables into query through textfields?

I am trying to create a register system for my MySQL database. I have a Java form that I created, in which the user inserts a username, password, and their email. I take that infromation and store it in a variable accordingly. The MySQL connection code works, and it does insert a new row, but the information is blank on the MySQL page. Am I doing someting wrong?
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JPasswordField passwordField;
private static Connection con;
private static PreparedStatement st;
private static int rs;
String username;
String password;
String email;
private JTextField textField_1;
String insertTableSQL = "INSERT INTO `users`" + "(username, password, email) VALUES" + "(?,?,?)";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
setResizable(false);
setTitle("Barrage : Login / Register");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 350, 200);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Username: ");
lblNewLabel.setBounds(60, 25, 68, 20);
contentPane.add(lblNewLabel);
JLabel lblPassword = new JLabel("Password: ");
lblPassword.setBounds(60, 59, 68, 20);
contentPane.add(lblPassword);
textField = new JTextField();
username = textField.getText();
textField.setBounds(138, 22, 120, 26);
contentPane.add(textField);
textField.setColumns(10);
passwordField = new JPasswordField();
password = passwordField.getText();
passwordField.setBounds(138, 56, 120, 26);
contentPane.add(passwordField);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/barrage", "root", "");
st = con.prepareStatement(insertTableSQL);
st.setString(1, username);
st.setString(2, password);
st.setString(3, email);
st.executeUpdate();
} catch(Exception e) {
e.printStackTrace();
}
}
});
btnRegister.setBounds(119, 138, 89, 23);
contentPane.add(btnRegister);
JLabel lblEmail = new JLabel("E-mail: ");
lblEmail.setBounds(60, 96, 68, 20);
contentPane.add(lblEmail);
textField_1 = new JTextField();
email = textField_1.getText();
textField_1.setBounds(138, 93, 120, 26);
contentPane.add(textField_1);
textField_1.setColumns(10);
}
}
You need to call the various fields' getText() method in your ActionListener so that you get the values after the user has entered them.
As it stands now you get the initial values prior to any user interaction.
You need to set the values of username u.a. in the moment where you you call the actionPerformed method.
Right now you set the value when creating the GUI. At that moment they are null. They are not "linked", they just take the value that the controls return at that time. If the controls getText() result changes, your variables do not get updated.

Categories

Resources