How can I make my table update? - java

I use SQLite. I have 2 JFrames. 1st is consists of table and "Load data", "Edit data". Click on Edit make the new, 2nd JFrame to appear. I want my table to be updated after I make some changes with a help of class Edit. How do I make it? One idea is to use ActionListener so that after I click save, delete or update buttons in JFrame2 method of Jframe 1, which stays for updating of the table(using query), is called. I have tried, but it does not work. I do not want the method of the 1 Jframe to be called in 2nd Jframe, I want this method to be called in 1st Jframe. What are possible solutions?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import javax.swing.*;
public class Diary extends JFrame {
private JPanel contentPane;
JTable table;
private JButton btnLoadData;
public void refreshTabel(){
try {
String query = "select * from Diary";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Diary frame = new Diary();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Diary() {
setResizable(false);
connection = Main.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1250, 650);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(34, 58, 1182, 530);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
btnLoadData = new JButton("Load data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select * from Diary";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnLoadData.setBounds(33, 17, 117, 29);
contentPane.add(btnLoadData);
JButton btnAddData = new JButton("Edit");
btnAddData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddData nw = new AddData();
nw.addData();
refreshTabel();
}
});
btnAddData.setBounds(153, 17, 117, 29);
contentPane.add(btnAddData);
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.sun.glass.events.WindowEvent;
import net.proteanit.sql.DbUtils;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
public class AddData extends JFrame {
private JPanel contentPane;
private JTextField Date;
private JTextField ExerciseName;
private JTextField Weight;
private JTextField Sets;
private JTextField Reps;
/**
* Launch the application.
* #return
*/
public static void addData() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddData frame = new AddData();
frame.setVisible(true);
frame.setAlwaysOnTop(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTextField Exercise;
private JTextField N;
/**
* Create the frame.
*/
public AddData() {
setTitle("Edit");
setResizable(false);
connection = Main.dbConnector();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 465, 368);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDate = new JLabel("Date");
lblDate.setBounds(29, 49, 61, 16);
contentPane.add(lblDate);
JLabel ExerciseLabel = new JLabel("Exercise");
ExerciseLabel.setBounds(29, 88, 90, 16);
contentPane.add(ExerciseLabel);
JLabel lblNewLabel_1 = new JLabel("Sets");
lblNewLabel_1.setBounds(29, 169, 61, 16);
contentPane.add(lblNewLabel_1);
JLabel lblReps = new JLabel("Reps");
lblReps.setBounds(29, 213, 61, 16);
contentPane.add(lblReps);
JLabel lblWeight = new JLabel("Weight");
lblWeight.setBounds(29, 126, 61, 16);
contentPane.add(lblWeight);
Date = new JTextField();
Date.setBounds(169, 56, 150, 26);
contentPane.add(Date);
Date.setColumns(10);
ExerciseName = new JTextField();
ExerciseName.setBounds(169, 60, 150, 26);
contentPane.add(ExerciseLabel);
ExerciseName.setColumns(10);
Weight = new JTextField();
Weight.setBounds(169, 132, 150, 26);
contentPane.add(Weight);
Weight.setColumns(10);
Sets = new JTextField();
Sets.setBounds(169, 170, 150, 26);
contentPane.add(Sets);
Sets.setColumns(10);
Reps = new JTextField();
Reps.setBounds(169, 208, 150, 26);
contentPane.add(Reps);
Reps.setColumns(10);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "insert into Diary (Date, Exercise, Weight, Sets, Reps) values (?,?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, Date.getText());
pst.setString(2, Exercise.getText());
pst.setString(3, Weight.getText());
pst.setString(4, Sets.getText());
pst.setString(5, Reps.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
btnSave.setBounds(29, 261, 117, 29);
contentPane.add(btnSave);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "update Diary set N ='"+N.getText()+"', Exercise ='"+Exercise.getText()+"', Weight ='"+Weight.getText()+"', Sets ='"+Sets.getText()+"', Reps ='"+Reps.getText()+"' where N ='"+N.getText()+"' ";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Updated");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
btnUpdate.setBounds(176, 261, 117, 29);
contentPane.add(btnUpdate);
Exercise = new JTextField();
Exercise.setBounds(169, 94, 150, 26);
contentPane.add(Exercise);
Exercise.setColumns(10);
N = new JTextField();
N.setBounds(169, 18, 150, 26);
contentPane.add(N);
N.setColumns(10);
JLabel lblN = new JLabel("N");
lblN.setBounds(29, 23, 61, 16);
contentPane.add(lblN);
JButton Delete = new JButton("Delete");
Delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "delete from Diary where N = '"+N.getText()+"'";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
Delete.setBounds(305, 261, 117, 29);
contentPane.add(Delete);
}
}

Related

why data is appearing multiple time after refreshing the button in jdbc swing table?

Here I have created a JTable and surround it with JScrollPane. I have created an update and refresh button so that I can refresh and update the values in the data set. But the problem is with the refresh button whenever I click the button it appears the data more than one time. Like I have 10 data set after updating the name when I refresh the button it is showing again 10 data means a total of 10+10=20 same types of data.
package insertData;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.mysql.cj.xdevapi.Statement;
import com.sun.jdi.connect.spi.Connection;
//import com.sun.tools.sjavac.pubapi.PubApi;
import java.awt.Color;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import javax.swing.JSplitPane;
public class Table_formate {
private JFrame frame;
private JTextField nametextField;
private JTextField idtextField;
private JTextField textFieldname;
private JTextField textFieldid;
private JTable table;
//Connection connection;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Table_formate window = new Table_formate();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Table_formate() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 539);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
nametextField = new JTextField();
nametextField.setBounds(140, 11, 152, 37);
frame.getContentPane().add(nametextField);
nametextField.setColumns(10);
idtextField = new JTextField();
idtextField.setColumns(10);
idtextField.setBounds(140, 68, 152, 37);
frame.getContentPane().add(idtextField);
JButton btnNewButton = new JButton("Submit");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");//load driver
java.sql.Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root"); //Establish connection
System.out.println("sucess");
String drop="insert into student values(?,?) ";
java.sql.PreparedStatement ps=((java.sql.Connection) connection).prepareStatement(drop);
//System.out.println(ps);
ps.setInt(1, Integer.parseInt(idtextField.getText()));
ps.setString(2, nametextField.getText());
System.out.println("id="+idtextField.getText()+" "+"name="+nametextField.getText());
ps.executeUpdate();
ps.close();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(324, 36, 89, 46);
frame.getContentPane().add(btnNewButton);
JLabel lblNewLabel = new JLabel("Name:");
lblNewLabel.setBounds(27, 11, 76, 37);
frame.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Id:");
lblNewLabel_1.setBounds(27, 68, 76, 37);
frame.getContentPane().add(lblNewLabel_1);
JButton Refreshbtn = new JButton("Refresh");
Refreshbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
DefaultTableModel tableModel=(DefaultTableModel) table.getModel();
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
java.sql.Statement stmt=((java.sql.Connection) connection).createStatement();
System.out.println("connection sucessful");
ResultSet rs= ((java.sql.Statement) stmt).executeQuery("select * from student order by id");
//PreparedStatement ps=connection.prepareStatement("select * from student order by id");
while ( rs.next()) {
String name=rs.getString("name");
int id=rs.getInt("id");
System.out.println(id+ "name="+name);
tableModel.addRow(new Object[] {id,name});
}
stmt.close();
rs.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Refreshbtn.setBounds(122, 139, 89, 30);
frame.getContentPane().add(Refreshbtn);
JLabel lblNewLabel_2 = new JLabel("Name:");
lblNewLabel_2.setBounds(27, 395, 76, 37);
frame.getContentPane().add(lblNewLabel_2);
JLabel lblNewLabel_1_1 = new JLabel("Id:");
lblNewLabel_1_1.setBounds(27, 452, 76, 37);
frame.getContentPane().add(lblNewLabel_1_1);
textFieldname = new JTextField();
textFieldname.setColumns(10);
textFieldname.setBounds(140, 395, 152, 37);
frame.getContentPane().add(textFieldname);
textFieldid = new JTextField();
textFieldid.setColumns(10);
textFieldid.setBounds(140, 452, 152, 37);
frame.getContentPane().add(textFieldid);
JButton btnUpdat = new JButton("update");
btnUpdat.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String drop="update student set name=? where id=?";
try {
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
PreparedStatement ps=((java.sql.Connection) connection).prepareStatement(drop);
ps.setString(1, textFieldname.getText());
ps.setInt(2, Integer.parseInt(textFieldid.getText()));
ps.executeUpdate();
System.out.println("Record updated");
ps.close();
Refreshbtn.doClick();
} catch (ClassNotFoundException | SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnUpdat.setBounds(324, 420, 89, 46);
frame.getContentPane().add(btnUpdat);
JButton btnEdit = new JButton("Edit");
btnEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel tableModel=(DefaultTableModel) table.getModel();
tableModel.fireTableDataChanged();
int row=table.getSelectedRow();
String name=(String) tableModel.getValueAt(row, 1);
String id=(String) tableModel.getValueAt(row, 0).toString();
textFieldid.setText(id);
textFieldname.setText(name);
}
});
btnEdit.setBounds(231, 139, 89, 30);
frame.getContentPane().add(btnEdit);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"id", "name"
}
));
table.setBounds(10, 203, 414, 167);
frame.getContentPane().add(table);
}
}
As #Abra mentioned, just clear the contents of your DefaultTableModel when refreshing and before adding the new data as follows:
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
tableModel.setRowCount(0);
tableModel.setColumnCount(0);
After cleaning the model, populate it again (in this example, adding some random user):
model.addColumn("id");
model.addColumn("Name");
Vector<String> userName = new Vector<>();
userName.add(user);
model.addRow(userName);

I want to present the username from database JAVA Jframe

I have two JFrame windows one for the login and the second for the welcome. Now I want to present the Firstname and the Lastname of the connected user near to the hello in the welcome screen.
I tried many things but none of them worked so I'm asking for you help. I just started to learn GUI:
The login code:
import java.awt.EventQueue;
import java.sql.*;
import javax.swing.*;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login {
private JFrame frame;
private JLabel MainLogo;
String Firstname=null;
String Lastname=null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
Connection connected = null;
private JTextField UsernameFiled;
private JPasswordField passwordField;
public Login() {
initialize();
connected = DBConnection.DBconnector();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 560, 256);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("UserName: ");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 20));
lblNewLabel.setBounds(160, 11, 140, 50);
frame.getContentPane().add(lblNewLabel);
JLabel lblPassword = new JLabel("PassWord: ");
lblPassword.setFont(new Font("Tahoma", Font.BOLD, 20));
lblPassword.setBounds(160, 72, 140, 40);
frame.getContentPane().add(lblPassword);
JButton Loginbtn = new JButton("Login");
Loginbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "Select * from Users where nickname=? and password=?";
PreparedStatement pst = connected.prepareStatement(query);
pst.setString(1, UsernameFiled.getText());
pst.setString(2, passwordField.getText());
ResultSet res = pst.executeQuery();
Firstname = res.getString("Firstname");
Lastname = res.getString("Lastname");
int c=0;
while(res.next()) {
c++;
}
if(c == 0) {
JOptionPane.showMessageDialog(null, "You didnt put any username or password!");
}
else if(c == 1) {
JOptionPane.showMessageDialog(null, "Hello to you, " + Firstname +" "+ Lastname);
frame.dispose();
UserPage UserFrame = new UserPage();
UserFrame.setVisible(true);
}else if( c > 1) {
JOptionPane.showMessageDialog(null, "Duplicate Username and Password");
}else {
JOptionPane.showMessageDialog(null, "Username and Password are inncorect...Try agian!");
}
pst.close();
res.close();
}catch(Exception LoginError) {
JOptionPane.showMessageDialog(null, LoginError);
}
}
});
Loginbtn.setFont(new Font("Tahoma", Font.BOLD, 20));
Loginbtn.setBounds(160, 148, 186, 40);
frame.getContentPane().add(Loginbtn);
UsernameFiled = new JTextField();
UsernameFiled.setFont(new Font("Tahoma", Font.BOLD, 16));
UsernameFiled.setBounds(310, 28, 186, 25);
frame.getContentPane().add(UsernameFiled);
UsernameFiled.setColumns(10);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Tahoma", Font.BOLD, 16));
passwordField.setBounds(310, 84, 186, 25);
frame.getContentPane().add(passwordField);
MainLogo = new JLabel("");
Image imgs = new ImageIcon(this.getClass().getResource("/login.png")).getImage();
MainLogo.setIcon(new ImageIcon(imgs));
MainLogo.setBounds(10, 11, 128, 128);
frame.getContentPane().add(MainLogo);
}
}
The Welcome Code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class UserPage extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserPage frame = new UserPage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connected=null;
private JTable table;
public UserPage() {
connected=DBConnection.DBPreconnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 576, 410);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton bntLoadData = new JButton("Show Users Data");
bntLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "Select ID,Age,Password,Firstname,Lastname from users";
PreparedStatement pst = connected.prepareStatement(query);
ResultSet res = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(res));
} catch (Exception Error) {
Error.printStackTrace();
}
}
});
JLabel lblNewLabel = new JLabel("Hello, " + "The Username name");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 18));
lblNewLabel.setBounds(10, 11, 280, 19);
contentPane.add(lblNewLabel);
bntLoadData.setFont(new Font("Tahoma", Font.BOLD, 20));
bntLoadData.setBounds(162, 102, 238, 23);
contentPane.add(bntLoadData);
table = new JTable();
table.setBounds(28, 136, 508, 221);
contentPane.add(table);
}
}
In your code, you does not seem to load the username or password of the logged in user at the welcome frame. Either you will have to pass that from the login frame or you will have to re-query the database and get firstname and lastname.
I suggest, simply pass the firstname and lastname from welcome screen via constructor.
In successful login, simply pass the name in the constructor: Login code addition:
} else if(c == 1) {
JOptionPane.showMessageDialog(null, "Hello to you, " + Firstname +" "+ Lastname);
frame.dispose();
UserPage UserFrame = new UserPage( Firstname, Lastname );
UserFrame.setVisible(true);
}
In the welcome frame, add a constructor to handle this:
public UserPage(String loggedInFirstName, String loggedInLastName){
// your remaining code
JLabel lblNewLabel = new JLabel("Hello, " + loggedInFirstName + " " + loggedInLastName );
// your remaining code.
}
A approach like this might work for your case and don't forget to mark the answer as accepted if this works for you

How to link multiple frames in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I created Login and Register frames separated which both connected to MySQL. If I just run the register frame, I can insert a new user to the database. However, If I run the login frame which includes the register frame inside and press register, the button that adds in the register frame does not work even the text fields are filled out.
//this is Login frame class
package YASAR;
import java.awt.BorderLayout;
import java.sql.*;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GirisEkrani extends JFrame {
static JButton btnKullancEkle = new JButton("Kullan\u0131c\u0131 Ekle");
public static JPanel contentPane;
private static JTextField textField;
private static JComboBox comboBox = new JComboBox();
private static JButton btnBalan = new JButton("Ba\u011Flan");
private static JLabel lblParola = new JLabel("Parola :");
private static JLabel lblXaampeBalanlamad = new JLabel("Xaampe Ba\u011Flan\u0131lamad\u0131");
//private static KullaniciEkle ke=new KullaniciEkle();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
lblXaampeBalanlamad.setVisible(false);
try {
GirisEkrani frame = new GirisEkrani();
frame.setVisible(true);
try {
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar","ozkan","******");
btnKullancEkle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
KullaniciEkle ke=new KullaniciEkle();
ke.setVisible(true);
}
});
btnBalan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
deneme abc=new deneme();
abc.setVisible(true);
}
});
con.close();
}
catch(SQLException e) {
textField.setEditable(false);
btnKullancEkle.setEnabled(false);
comboBox.setEnabled(false);
btnBalan.setEnabled(false);
lblParola.setVisible(false);
lblXaampeBalanlamad.setVisible(true);
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GirisEkrani() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 286, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(74, 129, 124, 19);
contentPane.add(textField);
textField.setColumns(10);
comboBox.setBounds(74, 42, 124, 21);
contentPane.add(comboBox);
btnBalan.setBounds(74, 184, 124, 33);
contentPane.add(btnBalan);
btnKullancEkle.setBounds(74, 227, 124, 26);
contentPane.add(btnKullancEkle);
lblParola.setBounds(10, 132, 45, 13);
contentPane.add(lblParola);
lblXaampeBalanlamad.setBounds(74, 90, 162, 29);
contentPane.add(lblXaampeBalanlamad);
}
}
// And this is register frame class where I add user
package YASAR;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.sql.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class KullaniciEkle extends JFrame {
public static JPanel contentPane;
public static JTextField textField;
public static JTextField textField_1;
public static JTextField textField_2;
public static JLabel lblIsim;
public static JLabel lblSoyisim;
public static JButton btnNewButton = new JButton("Ekle");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
KullaniciEkle frame = new KullaniciEkle();
frame.setVisible(true);
try {
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar","ozkan","******");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input="INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
try {
PreparedStatement ps=con.prepareStatement(input);
ps.setInt(1, Integer.parseInt(textField.getText()));
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
//ps.execute();
if(ps.executeUpdate()>0) {
JOptionPane.showMessageDialog(null, "user added","user add",JOptionPane.OK_CANCEL_OPTION);
}
}catch(SQLException f) {
f.printStackTrace();
}
finally {System.out.println("pressed");}
frame.setVisible(false);
new GirisEkrani().setVisible(true);
}
});
}
catch(SQLException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public KullaniciEkle() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 285, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(87, 67, 96, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(87, 112, 96, 19);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(87, 160, 96, 19);
contentPane.add(textField_2);
textField_2.setColumns(10);
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 10));
btnNewButton.setBounds(93, 232, 85, 21);
contentPane.add(btnNewButton);
JLabel lblTc = new JLabel("TC");
lblTc.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblTc.setBounds(10, 70, 45, 13);
contentPane.add(lblTc);
lblIsim = new JLabel("\u0130sim");
lblIsim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblIsim.setBounds(10, 115, 45, 13);
contentPane.add(lblIsim);
lblSoyisim = new JLabel("Soyisim");
lblSoyisim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblSoyisim.setBounds(10, 163, 45, 13);
contentPane.add(lblSoyisim);
}
}
You need to put this code inside your Constructor.
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input="INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
try {
PreparedStatement ps=con.prepareStatement(input);
ps.setInt(1, Integer.parseInt(textField.getText()));
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
//ps.execute();
if(ps.executeUpdate()>0) {
JOptionPane.showMessageDialog(null, "user added","user add",JOptionPane.OK_CANCEL_OPTION);
}
}catch(SQLException f) {
f.printStackTrace();
}
finally {System.out.println("pressed");}
frame.setVisible(false);
new GirisEkrani().setVisible(true);
}
});
Finally, it will look like this,
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.sql.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class KullaniciEkle extends JFrame {
public static JPanel contentPane;
public static JTextField textField;
public static JTextField textField_1;
public static JTextField textField_2;
public static JLabel lblIsim;
public static JLabel lblSoyisim;
public static JButton btnNewButton = new JButton("Ekle");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
KullaniciEkle frame = new KullaniciEkle();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public KullaniciEkle() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 285, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(87, 67, 96, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(87, 112, 96, 19);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(87, 160, 96, 19);
contentPane.add(textField_2);
textField_2.setColumns(10);
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 10));
btnNewButton.setBounds(93, 232, 85, 21);
contentPane.add(btnNewButton);
JLabel lblTc = new JLabel("TC");
lblTc.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblTc.setBounds(10, 70, 45, 13);
contentPane.add(lblTc);
lblIsim = new JLabel("\u0130sim");
lblIsim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblIsim.setBounds(10, 115, 45, 13);
contentPane.add(lblIsim);
lblSoyisim = new JLabel("Soyisim");
lblSoyisim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblSoyisim.setBounds(10, 163, 45, 13);
contentPane.add(lblSoyisim);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnNewButtonActionPerformed(e);
}
});
}
private void btnNewButtonActionPerformed(ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar", "ozkan", "******");
String input = "INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
try {
PreparedStatement ps = con.prepareStatement(input);
ps.setInt(1, Integer.parseInt(textField.getText()));
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
//ps.execute();
if (ps.executeUpdate() > 0) {
JOptionPane.showMessageDialog(null, "user added", "user add", JOptionPane.OK_CANCEL_OPTION);
}
} catch (SQLException f) {
f.printStackTrace();
} finally {
System.out.println("pressed");
}
//Instead of frame use this keyword
this.setVisible(false);
new GirisEkrani().setVisible(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
NOTE:- This is not the best practice to communicate with the database.

Not able to call Jframe from a contentpane

i was trying to build this management system.
the login page is the main page if the user forgets their password then they can click on the forget password to change the password.
but,
whenever i call the forgot password from login frame, a small window opens rather than the coded window of forget page.
NOTE:the forget window runs fine when executed alone.
login page
`package hM_prac;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPasswordField;
import java.sql.*;
public class login extends JFrame implements ActionListener {
private JPanel contentPane;
private JTextField txtUsername;
private JPasswordField pwdwhatever;
JLabel lblNewLabel,lblNewLabel_1,lblNewLabel_2;
JButton btnForgotPassword ,btnSignUp,btnLogin;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
login frame = new login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection con;
PreparedStatement ps;
ResultSet rs;
/**
* Create the frame.
*/
public login() {
super("LOGIN");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 465, 300);
contentPane = new JPanel();
contentPane.setBorder(new LineBorder(new Color(0, 0, 0)));
setContentPane(contentPane);
contentPane.setLayout(null);
lblNewLabel = new JLabel("Welcome to MYHOTEL");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Verdana", Font.PLAIN, 18));
lblNewLabel.setBounds(10, 11, 414, 23);
contentPane.add(lblNewLabel);
txtUsername = new JTextField();
txtUsername.setText("");
txtUsername.setBounds(222, 96, 94, 20);
contentPane.add(txtUsername);
txtUsername.setColumns(20);
lblNewLabel_1 = new JLabel("Username:");
lblNewLabel_1.setLabelFor(txtUsername);
lblNewLabel_1.setBounds(121, 99, 69, 14);
contentPane.add(lblNewLabel_1);
lblNewLabel_2 = new JLabel("Password:");
lblNewLabel_2.setBounds(121, 138, 69, 14);
contentPane.add(lblNewLabel_2);
btnLogin = new JButton("Login");
btnLogin.setBounds(169, 166, 89, 23);
contentPane.add(btnLogin);
btnSignUp = new JButton("Sign Up");
btnSignUp.setBounds(305, 215, 89, 23);
contentPane.add(btnSignUp);
btnForgotPassword = new JButton("Forgot password");
btnForgotPassword.setBounds(37, 215, 135, 23);
contentPane.add(btnForgotPassword);
pwdwhatever = new JPasswordField();
pwdwhatever.setText("");
pwdwhatever.setBounds(222, 136, 94, 17);
contentPane.add(pwdwhatever);
btnLogin.addActionListener(this);
btnSignUp.addActionListener(this);
btnForgotPassword.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
Object o=ae.getSource();
if(o==btnLogin)
{
String uname,pass;
uname=txtUsername.getText();
pass=pwdwhatever.getText();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","hm","hm");
ps=con.prepareStatement("select * from account where username=? and password=?");
ps.setString(1,uname);
ps.setString(2,pass);
rs=ps.executeQuery();
if(rs.next())
{
System.out.println("Valid User.");
JOptionPane.showMessageDialog(this,"Valid User","Done",JOptionPane.INFORMATION_MESSAGE);
this.dispose();
rs.close();
ps.close();
//new homepage();
}
else
{
JOptionPane.showMessageDialog(this,"Incorrect","Error",JOptionPane.ERROR_MESSAGE);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
if(o==btnSignUp)
{
this.dispose();
new sign_up().setVisible(true);
}
if(o==btnForgotPassword)
{
this.dispose();
new forget().setVisible(true);
}
}
}
`
forget page
` package hM_prac;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPasswordField;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class forget extends JFrame implements ActionListener {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JPasswordField passwordField;
JButton btnSubmit,btnSubmitAnswer;
JLabel label,lblNewLabel_3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
System.out.println("hh");
forget window = new forget();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public forget() {
//super("login");
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 374, 358);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBackground(Color.BLACK);
lblNewLabel.setBounds(18, 77, 92, 14);
frame.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Security Question:");
lblNewLabel_1.setBackground(Color.BLACK);
lblNewLabel_1.setBounds(18, 139, 132, 14);
frame.getContentPane().add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("Answer:");
lblNewLabel_2.setBackground(Color.BLACK);
lblNewLabel_2.setBounds(18, 164, 92, 14);
frame.getContentPane().add(lblNewLabel_2);
//frame.getContentPane().add(lblNewLabel_3);
JLabel lblNewLabel_5 = new JLabel("Forgot password");
lblNewLabel_5.setFont(new Font("Tahoma", Font.BOLD, 19));
lblNewLabel_5.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel_5.setBounds(10, 11, 338, 23);
frame.getContentPane().add(lblNewLabel_5);
textField = new JTextField();
textField.setBackground(Color.WHITE);
textField.setBounds(156, 77, 182, 14);
frame.getContentPane().add(textField);
textField.setColumns(10);
btnSubmit = new JButton("Submit ");
btnSubmit.setBackground(Color.WHITE);
btnSubmit.setBounds(184, 102, 142, 23);
frame.getContentPane().add(btnSubmit);
label = new JLabel("..");
label.setBackground(Color.BLACK);
label.setBounds(160, 139, 178, 14);
frame.getContentPane().add(label);
textField_1 = new JTextField();
textField_1.setBounds(156, 164, 192, 14);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
btnSubmitAnswer = new JButton("Submit Answer");
btnSubmitAnswer.setBackground(Color.WHITE);
btnSubmitAnswer.setBounds(184, 189, 142, 23);
frame.getContentPane().add(btnSubmitAnswer);
//frame.getContentPane().add(btnSubmitPassword);
btnSubmit.addActionListener(this);
btnSubmitAnswer.addActionListener(this);
}
Connection con;
PreparedStatement ps;
ResultSet rs;
private JButton btnSubmitPassword;
public void actionPerformed(ActionEvent ae) {
Object o=ae.getSource();
String uname;
if(o==btnSubmit)
{ System.out.println("ques");
uname=textField.getText();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","hm","hm");
ps=con.prepareStatement("select security_question from account where username=?");
ps.setString(1,uname);
rs=ps.executeQuery();
if(rs.next())
{
String secq=rs.getString("security_question");
System.out.println("question"+secq);
label.setText(secq);
frame.getContentPane().add(label);
}
else if(rs==null){
JOptionPane.showMessageDialog(this,"No such user","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(this,"Invalid User","Error",JOptionPane.ERROR_MESSAGE);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
else if(o==btnSubmitAnswer)
{
//System.out.println("jj");
String ans;
uname=textField.getText();
ans=textField_1.getText();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","hm","hm");
ps=con.prepareStatement("select * from account where username=? and answer=?");
ps.setString(1,uname);
ps.setString(2,ans);
rs=ps.executeQuery();
if(rs!=null)
{
System.out.println("jj");
lblNewLabel_3 = new JLabel("New Password:");
lblNewLabel_3.setBackground(Color.BLACK);
lblNewLabel_3.setBounds(18, 226, 117, 14);
frame.getContentPane().add(lblNewLabel_3);
passwordField = new JPasswordField();
passwordField.setBackground(Color.BLACK);
passwordField.setBounds(160, 226, 178, 17);
//frame.getContentPane().add(passwordField);
frame.getContentPane().add(passwordField);
btnSubmitPassword = new JButton("Submit password");
btnSubmitPassword.setBounds(82, 285, 182, 23);
frame.getContentPane().add(btnSubmitPassword);
btnSubmitPassword.addActionListener(this);
}
else{
JOptionPane.showMessageDialog(this,"Wrong answer","Error",JOptionPane.ERROR_MESSAGE);
}
}catch(Exception e){
e.printStackTrace();
}
}
else if(o==btnSubmitPassword){
String pass;
uname=textField.getText();
pass=passwordField.getText();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","hm","hm");
ps=con.prepareStatement("update account set password=? where username=?");
ps.setString(1,pass);
ps.setString(1,uname);
rs=ps.executeQuery();
if(rs==null)
{
JOptionPane.showMessageDialog(this,"Error","Error",JOptionPane.ERROR_MESSAGE);
}
else{
JOptionPane.showMessageDialog(this,"Password reset","Error",JOptionPane.ERROR_MESSAGE);
this.dispose();
new login();
}}catch(Exception e){
e.printStackTrace();
}
}
}
}
`
Here is a better way to show another window from a JFrame (as is in this case of showing a "forgot password" window from "login" window) is to define it as a modal JDialog. Here is some working code to demonstrate what is possible:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainWindow {
public static void main(String [] args) {
new MainWindow();
}
private JFrame frame;
public MainWindow() {
frame = new JFrame("Main Window - login");
JButton button = new JButton("Click me to open dialog");
button.addActionListener(new ButtonListener());
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 300);
frame.setLocation(200, 200);
frame.setVisible(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
new DialogWindow();
}
}
}
class DialogWindow {
DialogWindow() {
JDialog dialog = new JDialog();
dialog.setTitle("Dialog - forgot");
dialog.setModal(true);
dialog.add(new JLabel("Do something here..."));
dialog.setSize(250, 150);
dialog.setLocation(600, 200);
dialog.setVisible(true);
}
}
In the above code the MainWindow can be assumed as the login window and the DialogWindow as the forgot password dialog. When the user clicks the button in the login window, the forgot dialog opens as a modal window. Then the user does some work in the forgot dialog; and on closing it returns to the main window.
Here is a link to Oracle's Java Swing tutorials with examples of how to use JFrame, JDialog and other GUI components.

java sql queries

I have a query. I have a database, and I am trying to write code, so that a record in the database can be created from the java software.
I have a connector class that connects to the database, then a registerStudent class, that lets the user type in value into 2 textfields. then the values should be used to create a record in the database table.
when i hit the submit button it gives me this error code:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at RegisterStudent$2.actionPerformed(RegisterStudent.java:99)
FYI - Line 99 Code =
con.stmt.executeUpdate("INSERT INTO staff (Name, Profession)"+"VALUES"+"("+"'"+name+"',"+"'"+profession+"')");
This is my code for the registerStudent class:
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
public class RegisterStudent
{
public RegisterStudent() {
initialize();
}
public JFrame frmRegisterStudent;
Connector con;
private JTextField textField_1;
private JTextField textField_2;
// initialise the frame
private void initialize() {
frmRegisterStudent = new JFrame();
frmRegisterStudent.setTitle("LEC AdminPro: RegisterStudents");
frmRegisterStudent.setBounds(100, 100, 413, 225);
frmRegisterStudent.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frmRegisterStudent.setLocationRelativeTo(null);
Border border = LineBorder.createGrayLineBorder();
frmRegisterStudent.getContentPane().setLayout(null);
con = new Connector();
JPanel panel_1 = new JPanel();
panel_1.setBounds(0, 0, 397, 189);
frmRegisterStudent.getContentPane().add(panel_1);
panel_1.setBorder(border);
panel_1.setLayout(null);
JLabel lblRegister = new JLabel("Register Student");
lblRegister.setFont(new Font("Tahoma", Font.BOLD, 12));
lblRegister.setBounds(10, 11, 124, 20);
panel_1.add(lblRegister);
JLabel lblSurname = new JLabel("Name");
lblSurname.setFont(new Font("Arial", Font.PLAIN, 11));
lblSurname.setBounds(10, 63, 69, 14);
panel_1.add(lblSurname);
JLabel lblDob = new JLabel("Profession");
lblDob.setFont(new Font("Arial", Font.PLAIN, 11));
lblDob.setBounds(10, 88, 69, 14);
panel_1.add(lblDob);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(104, 63, 266, 20);
panel_1.add(textField_1);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(104, 88, 266, 20);
panel_1.add(textField_2);
JButton btnNewButton = new JButton("Cancel");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Object[] options = {"Yes", "No"};
Component form = null;
int n = JOptionPane.showOptionDialog(form, "Would you like to cancel the new Registration?", "Exit Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options);
if(n == JOptionPane.YES_OPTION) {
frmRegisterStudent.setVisible(false);
}
}
});
btnNewButton.setBounds(280, 119, 89, 23);
panel_1.add(btnNewButton);
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String name = textField_1.getText();
String profession = textField_1.getText();
try {
con.stmt.executeUpdate("INSERT INTO staff (Name, Profession)"+"VALUES"+"("+"'"+name+"',"+"'"+profession+"')");
JOptionPane.showMessageDialog(frmRegisterStudent, "New Record has been added");
} catch (SQLException e) {
System.out.println("Record couldn't be added!");
e.printStackTrace();
}
}
});
button.setBounds(181, 119, 89, 23);
panel_1.add(button);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RegisterStudent window = new RegisterStudent();
window.frmRegisterStudent.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
public void setVisible(boolean b) {
frmRegisterStudent.setVisible(true);
}
}
It looks like the problem is in the Connector class, which has a stmt field that does not get initialized.
Use this instead of the line with the NullPointerException
con.stmt = con.conn.prepareStatement("insert into staff (name, profession) values (?, ?)");
con.stmt.setString(1, name);
con.stmt.setString(2, profession);
con.stmt.executeUpdate();
But note that this is pretty bad design.
Is your connector null? I see the stmt is a field in the connector, have you initialized it?
By the way using a prepared statement is much better in your case, because it will escape the Strings (for example if they have "'" in them).
PreparedStatement pstmt = connection.prepareStatement("insert into staff (name, profession) values (?, ?)");
pstmt.setString(1, name);
pstmt.setString(2, profession);
pstmt.executeUpdate();

Categories

Resources