Adding values to JTable as dynamicly - java

I have a textbox which sent something to database and jtable list the values from database. But when i add something to database. Jtable dont show it in same time. when i close the program and debug again, it shows that time. I want Jtabel to show textbox value when i click the save button. How can i create a dynamic jtable?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Topic extends JFrame {
private static final long serialVersionUID = 1L;
JFrame frmTopic;
JPanel pnl, pnl_generaltopic;
static JTextField txt_topic;
JLabel lbl_topicNme, lbl_topicpage;
JButton btn_close, btn_update, btn_save;
public static Connection con = null;
public static ResultSet rs = null;
public static Statement st = null;
static Vector<Vector<String>> data = new Vector<Vector<String>>();
private JScrollPane scrollPane;
private static JTable table;
public Topic() {
pnl_generaltopic = new JPanel();
pnl_generaltopic.setBackground(Color.lightGray);
pnl_generaltopic.setLayout(null);
frmTopic = new JFrame("Topic");
frmTopic.addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent arg0) {
con = Dbconnect.conect();
}
});
frmTopic.setTitle("E-TEST");
frmTopic.setBounds(100, 100, 500, 500);
frmTopic.setVisible(true);
frmTopic.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTopic.getContentPane().setLayout(new BorderLayout(0, 0));
frmTopic.getContentPane().add(pnl_generaltopic);
topicPanel();
topicTable();
}
public void topicPanel() {
JPanel panel_addingNewTopic = new JPanel();
panel_addingNewTopic.setBounds(10, 0, 464, 203);
pnl_generaltopic.add(panel_addingNewTopic);
panel_addingNewTopic.setLayout(null);
btn_save = new JButton("Save");
btn_save.setBounds(65, 166, 67, 23);
panel_addingNewTopic.add(btn_save);
btn_update = new JButton("Update");
btn_update.setBounds(142, 162, 90, 30);
panel_addingNewTopic.add(btn_update);
btn_close = new JButton("Close");
btn_close.setBounds(240, 162, 90, 30);
panel_addingNewTopic.add(btn_close);
txt_topic = new JTextField();
txt_topic.setBounds(65, 59, 270, 71);
panel_addingNewTopic.add(txt_topic);
lbl_topicNme = new JLabel("Topic Name");
lbl_topicNme.setBounds(10, 65, 150, 59);
panel_addingNewTopic.add(lbl_topicNme);
lbl_topicpage = new JLabel("Topic Page");
lbl_topicpage.setBounds(10, 11, 300, 20);
panel_addingNewTopic.add(lbl_topicpage);
lbl_topicpage.setFont(new Font("arial", Font.BOLD, 15));
btn_close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmTopic.dispose();
}
}
);
btn_save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
st = con.createStatement();
String sorgu = "insert into topic " + "(topicname)"
+ "VALUES ('" + txt_topic.getText() + "')";
st.executeUpdate(sorgu);
JOptionPane.showMessageDialog(Topic.this, "Topic was added");
} catch (Exception s) {
System.out.print(s.getMessage());
}
}
}
);
}
public void topicTable() {
scrollPane = new JScrollPane();
scrollPane.setBounds(10, 226, 464, 190);
pnl_generaltopic.add(scrollPane);
Vector<String> headers = new Vector<String>();
headers.add("Topic Name");
getData();
//this is the model which contain actual body of JTable
DefaultTableModel model = new DefaultTableModel(data, headers);
table = new JTable(model);
scrollPane.setColumnHeaderView(table);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//table=new JTable(model);
//table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
header_size();
//JScrollPane scroll = new JScrollPane(table);
scrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pack();
setResizable(false);
setVisible(true);
}
/**
* Setting the particular Column Size in JTable
*/
public static void header_size() {
TableColumn column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(350);
}
/**
* Fetching Data From MySql Database
* and storing in a Vector of a Vector
* to Display in JTable
*/
private static void getData() {
// Enter Your MySQL Database Table name in below Select Query.
String str = "select * from topics";
Connection con;
ResultSet rs;
Statement st;
try {
con = DriverManager.getConnection("jdbc:mysql://" + "localhost:3306/database", "root", "1234");
st = con.createStatement();
rs = st.executeQuery(str);
while (rs.next()) {
Vector<String> d = new Vector<String>();
d.add(rs.getString("topicname"));
d.add("\n\n\n\n\n\n\n");
data.add(d);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Topic topic = new Topic();
topic.setVisible(false);
}
}

You can use the addRow(...) method of the DefaultTableModel to dynamically add a row of data in the model.
So if the update to your database is successful, then you would invoke the addRow() method.
Also, you should use a PreparedStatement when using SQL. It will make creating the SQL easier since you don't need to worry about the delimiters. Simple example to give you an idea:
String sql = "INSERT INTO Page (Name, Title) VALUES (?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, "Name1" );
stmt.setString( 2, textField.getText() );
stmt.executeUpdate();

Related

Basic Swing GUI with JDBC connection filling labels with info from query

Currently, I have created a Swing GUI to pull data from a basic database.
Eventually, I want to build this into a point of sale system and this is the start.
Once I get the "basics" down I will be able to expand it with different tabs and more items.
For now the query is able to pull the data and I can get the code to print to the console, but when I try to implement it to each label, or text box it will only display on one text box, and not others.
Is a loop needed to cycle through each of my labels, as they are labeled label1, label2...? Then how do I ensure the SQL query loads to each label? In the loop do I sort of the productID?
I tried using multiple queries and get a result set is closed error, and figured there is an easier way to get the data.
Here is the code:
package application;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.BoxLayout;
import javax.swing.JDesktopPane;
public class Application extends JFrame {
private JTextField prc2;
private JTextField prc1;
//private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Application frame = new Application();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Application() {
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JDesktopPane desktopPane = new JDesktopPane();
getContentPane().add(desktopPane);
prc2 = new JTextField();
prc2.setBounds(70, 111, 86, 20);
desktopPane.add(prc2);
prc2.setColumns(10);
prc1 = new JTextField();
prc1.setBounds(70, 80, 86, 20);
desktopPane.add(prc1);
prc1.setColumns(10);
JLabel item1 = new JLabel("New label");
item1.setBounds(10, 83, 46, 14);
desktopPane.add(item1);
JLabel item2 = new JLabel("New label");
item2.setBounds(10, 114, 46, 14);
desktopPane.add(item2);
JLabel qty1 = new JLabel("New label");
qty1.setBounds(181, 83, 46, 14);
desktopPane.add(qty1);
JLabel qty2 = new JLabel("New label");
qty2.setBounds(181, 114, 46, 14);
desktopPane.add(qty2);
JLabel qty = new JLabel("Quantity");
qty.setBounds(181, 40, 46, 14);
desktopPane.add(qty);
JLabel Price = new JLabel("PRICE");
Price.setBounds(70, 40, 46, 14);
desktopPane.add(Price);
Connection conn = null;
//Statement stmt = null;
//ObservableList<String> data = FXCollections.observableArrayList();
try {
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName = Capstone; username=dbuser; password=password";
conn = DriverManager.getConnection(dbURL);
Statement stmt = conn.createStatement();
String sqlStmt = "SELECT * FROM dbo.products WHERE ProductID = 1";
ResultSet rs = stmt.executeQuery(sqlStmt);
while (rs.next()) {
int id = rs.getInt("ProductID");
String productName = rs.getString("productName");
String quant = rs.getString("productQty");
String price = rs.getString("ProductPrice");
item1.setText(productName);
qty1.setText(quant);
prc1.setText(price);
}
String sqlStmt1 = "SELECT * FROM dbo.products WHERE ProductID = 2";
ResultSet rs1 = stmt.executeQuery(sqlStmt1);
while (rs1.next()) {
int id1 = rs.getInt("ProductID");
String productName1 = rs.getString("productName");
String quant1 = rs.getString("productQty");
String price1 = rs.getString("ProductPrice");
item2.setText(productName1);
qty2.setText(quant1);
prc2.setText(price1);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
If I missed a question that is similar please point me in the right direction.

populate JTable with the value selected in Jcombobox

I have a JCombobox and JTable
and database
jcombobox is filled with the value of first_name of student table from databse.
Whenever I select a name from database I want the value of Course name from course and student_score from score table of the database to be displayed in Jtable.
Basically I want to display the records of selected in JComboBox in Jtable
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 java.awt.Font;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.*;
import java.sql.*;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.PopupMenuEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ShowScore extends JFrame {
private JPanel contentPane;
private JTable table;
private JComboBox comboBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ShowScore frame = new ShowScore();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection con=null;
Score s=new Score();
public ShowScore() {
con=MyConnection.getConnection();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1238, 761);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblScoreSheet = new JLabel("Score Sheet");
lblScoreSheet.setFont(new Font("Times New Roman", Font.BOLD, 28));
lblScoreSheet.setBounds(500, 33, 155, 50);
contentPane.add(lblScoreSheet);
JPanel panel = new JPanel();
panel.setBounds(24, 259, 720, 426);
contentPane.add(panel);
panel.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 13, 675, 452);
panel.add(scrollPane);
comboBox = new JComboBox();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
table = new JTable();
scrollPane.setViewportView(table);
try {
String n=(String)comboBox.getSelectedItem();
String sql="SELECT score.student_id, student.first_name, student.last_name,course.subject, score.student_score FROM ((score INNER JOIN student ON score.student_id=student.id)\r\n" +
" INNER JOIN course ON score.course_id=course.cid WHERE student.first_name=n)";
PreparedStatement ps=con.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
JLabel lblName = new JLabel("Name:");
lblName.setFont(new Font("Times New Roman", Font.PLAIN, 18));
lblName.setBounds(102, 107, 56, 16);
contentPane.add(lblName);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
s.fillScoreCombo(comboBox);
comboBox.setBounds(171, 105, 260, 27);
contentPane.add(comboBox);
table = new JTable();
scrollPane.setViewportView(table);
try {
String n=(String)comboBox.getSelectedItem();
String sql="SELECT score.student_id, student.first_name, student.last_name,course.subject, score.student_score FROM ((score INNER JOIN student ON score.student_id=student.id)\r\n" +
" INNER JOIN course ON score.course_id=course.cid)";
PreparedStatement ps=con.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
JLabel lblName = new JLabel("Name:");
lblName.setFont(new Font("Times New Roman", Font.PLAIN, 18));
lblName.setBounds(102, 107, 56, 16);
contentPane.add(lblName);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
String n=(String)comboBox.getSelectedItem();
String sql="SELECT .... WHERE student.first_name=n)";
That code doesn't do anything with the variable "n". You can't just include "n" as part of the String because all the have is the character "n", not the value of the variable.
You were given a link to a tutorial on using a PreparedStatement in your last question (Populate JTable with the value in JCombobox).
So where do you use the "?" which indicates you want to provide a dynamic value to the SQL statement?
Your basic code should be:
String sql="SELECT ..... where student.first_name = ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, n);
ResultSet rs = ps.executeQuery();
Now the value of the variable "n" will replace the "?" in the SQL string.
Assuming the rest of your SQL is correct then it should work.

How to trigger Jtable update after delete or insert in DB?

I don't know how to refresh data in JTable after delete or after insert from other JDialog. I tried to initiate with calling tabela(); after delete to refresh data in JTable but that don't work.
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class LekariD extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTable table;
private String lekar;
private DefaultTableModel model1;
public static void main(String[] args) {
try {
LekariD dialog = new LekariD();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
dialog.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
Connection con = null;
public void tabela () {
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
try {
String sql = "Select * from lekari";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery( sql );
java.sql.ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
columnNames.addElement("Ime Lekara");
columnNames.addElement("LBO");
while (rs.next()) {
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
} catch (Exception e) {
System.out.println( e );
}
model1 = new DefaultTableModel(data, columnNames) {
#Override
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
}
}
return Object.class;
}
};
}
/**
* Create the dialog.
*/
public LekariD() {
con = DatabaseConnector.dbConnector();
tabela();
setBounds(100, 100, 514, 654);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 126, 339, 478);
contentPanel.add(scrollPane);
table = new JTable(model1);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
DefaultTableModel model=(DefaultTableModel)table.getModel();
int selectedRowIndex = table.getSelectedRow();
lekar = model.getValueAt(selectedRowIndex, 0).toString();
}
});
table.setFillsViewportHeight(true);
scrollPane.setViewportView(table);
JButton btnNewButton = new JButton("Unos");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
NoviLekarD nl = new NoviLekarD();
nl.setLocationRelativeTo(null);
nl.setVisible(true);
}
});
btnNewButton.setBounds(359, 126, 129, 44);
contentPanel.add(btnNewButton);
JButton btnNewButton_1 = new JButton("Brisanje");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "delete from lekari where ime_lekar = '"+lekar+"' ";
Statement stmt1 = con.prepareStatement(query);
stmt1.executeUpdate(query);
stmt1.close();
JOptionPane.showMessageDialog(contentPanel, "Uspešno obrisan podatak", "Brisanje !", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e2) {
System.out.println( e2 );
}
//tabela(); - tried with this but don't work
}
});
btnNewButton_1.setBounds(359, 212, 129, 44);
contentPanel.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Izlaz");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
con.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
dispose();
}
});
btnNewButton_2.setBounds(359, 560, 129, 44);
contentPanel.add(btnNewButton_2);
JLabel lblSpisakLekara = new JLabel("Spisak lekara");
lblSpisakLekara.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
lblSpisakLekara.setBounds(10, 42, 139, 38);
contentPanel.add(lblSpisakLekara);
}
}
Let's take a look at what's happening:
When you call tabela() you query the database and create a new DefaultTableModel in model1.
During construction in LekariD() you create a new instance of JTable and provide it with model1.
On change you update the database and call tabela() again. This creates a new DefaultTableModel in model1. Your table still holds the previous DefaultTableModel and queries it whenever you require some data to be drawn.
So, what you have to do after tabela() is to provide your table with the new table model:
table.setModel(model1);
This let's your table know about the new data and makes it recalculate columns, redraw itself, etc.

Updating JTable in GUI from MySQL

I have created a GUI which connects to the db, displays the db information in a JTable displayed in a JFrame however when using the add data button I am getting the message that data has been added to MySQL but the table does not update? After this the next step is to update / delete entries and also display this in the table.
I am relatively new to GUI's in Java and was just wondering if I am missing a method as I thought the populateTable(); function should do this automatically from my populateTable(); method.
This is everything I have written so far
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
import net.proteanit.sql.DbUtils;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComboBox;
import javax.swing.JTextPane;
public class GUI3 extends JFrame {
private static final long serialVersionUID = 1L;
// DB Code
DBHelper dbhelper = new DBHelper();
Connection con = dbhelper.open();
Statement st;
ResultSet rs;
DefaultTableModel model = new DefaultTableModel();
private JPanel contentPane;
private JTable table;
private JTextField userText;
private JTextField ageText;
private JTextField surText;
private JTextField genreText;
private JTextField hairText;
private JTextField genderText;
private JTextField firstText;
private GUI3 frame;
private final Action action = new SwingAction();
/**
* Launch the application.
*/
public void main() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new GUI3();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void getUsersDataFromDB() {
try {
st = con.createStatement();
String searchQuery = "SELECT * FROM user";
rs = st.executeQuery(searchQuery);
} catch (Exception ex) {
System.out.println(ex.getMessage());
JOptionPane.showMessageDialog(null, (ex.getMessage()));
}
}
private void populateTable() {
getUsersDataFromDB();
table.setModel(DbUtils.resultSetToTableModel(rs));
JTableHeader th = table.getTableHeader();
TableColumnModel tcm = th.getColumnModel();
tcm.getColumn(0).setHeaderValue("User id");
tcm.getColumn(1).setHeaderValue("Genre");
tcm.getColumn(2).setHeaderValue("Hair Length");
tcm.getColumn(3).setHeaderValue("Name");
tcm.getColumn(4).setHeaderValue("Surname");
tcm.getColumn(5).setHeaderValue("Age");
tcm.getColumn(6).setHeaderValue("Gender");
th.repaint();
}
/**
* Create the frame.
*/
public GUI3() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 426);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(17, 5, 548, 167);
userText = new JTextField();
userText.setBounds(17, 180, 70, 20);
userText.setColumns(10);
ageText = new JTextField();
ageText.setBounds(415, 180, 75, 20);
ageText.setColumns(10);
surText = new JTextField();
surText.setBounds(335, 180, 75, 20);
surText.setColumns(10);
genreText = new JTextField();
genreText.setBounds(95, 180, 75, 20);
genreText.setColumns(10);
JButton addButton = new JButton("Add");
addButton.setBounds(85, 225, 100, 25);
addButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
String searchQuery = "INSERT INTO `user`(`user_id`, `genre_id`, `hair_length`, "+ "`user_fname`,`user_lname`,`user_age`,`user_gender`) " + "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement insert = con.prepareStatement(searchQuery)) {
insert.setString(1, userText.getText());
insert.setString(2, genreText.getText());
insert.setString(3, hairText.getText());
insert.setString(4, firstText.getText());
insert.setString(5, surText.getText());
insert.setString(6, ageText.getText());
insert.setString(7, genderText.getText());
JOptionPane.showMessageDialog(null, "Data Added To MySQL");
}catch(Exception ex){
ex.printStackTrace();
}
populateTable();
}
});
// Update Button Functionality
JButton updateButton = new JButton("Update");
updateButton.setBounds(185, 225, 100, 25);
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String searchQuery = "UPDATE user (user_id, genre_id, hair_length, " + "user_fname, user_lname, user_age, user_gender) " + "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement insert = con.prepareStatement(searchQuery))
{
insert.setString(1, userText.getText());
insert.setString(2, genreText.getText());
insert.setString(3, hairText.getText());
insert.setString(4, firstText.getText());
insert.setString(5, surText.getText());
insert.setString(6, ageText.getText());
insert.setString(7, genderText.getText());
JOptionPane.showMessageDialog(null, "Database Updated");
}
catch(Exception ex)
{
ex.printStackTrace();
}
populateTable();
}
});
// Delete Button Functionality
JButton deleteButton = new JButton("Delete");
deleteButton.setBounds(285, 225, 100, 25);
deleteButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String searchQuery = "DELETE FROM USER WHERE (user_id, genre_id, hair_length, " + "user_fname, user_lname, user_age, user_gender) " + "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement insert = con.prepareStatement(searchQuery)) {
insert.setString(1, userText.getText());
insert.setString(2, genreText.getText());
insert.setString(3, hairText.getText());
insert.setString(4, firstText.getText());
insert.setString(5, surText.getText());
insert.setString(6, ageText.getText());
insert.setString(7, genderText.getText());
JOptionPane.showMessageDialog(null, "Database Updated");
}catch(Exception ex){
ex.printStackTrace();
}
}
});
hairText = new JTextField();
hairText.setBounds(175, 180, 75, 20);
hairText.setColumns(10);
genderText = new JTextField();
genderText.setBounds(495, 180, 70, 20);
genderText.setColumns(10);
firstText = new JTextField();
firstText.setBounds(255, 180, 75, 20);
firstText.setColumns(10);
table = new JTable();
populateTable();
scrollPane.setViewportView(table);
contentPane.setLayout(null);
contentPane.add(firstText);
contentPane.add(scrollPane);
contentPane.add(userText);
contentPane.add(genreText);
contentPane.add(hairText);
contentPane.add(surText);
contentPane.add(ageText);
contentPane.add(genderText);
contentPane.add(addButton);
contentPane.add(updateButton);
contentPane.add(deleteButton);
JComboBox comboBox = new JComboBox();
comboBox.setBounds(35, 285, 75, 20);
contentPane.add(comboBox);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBounds(35, 310, 75, 20);
contentPane.add(comboBox_1);
JComboBox comboBox_2 = new JComboBox();
comboBox_2.setBounds(35, 335, 75, 20);
contentPane.add(comboBox_2);
JTextPane textPane = new JTextPane();
textPane.setBounds(285, 285, 270, 75);
contentPane.add(textPane);
}
}
you need to refresh your table after update, delete or add, for that first clear your table then fill the table again , immediately after or before you show the message dialog Successfully added/updated/deleted or whatever
JOptionPane.showMessageDialog(null, "Database Updated");
model.setRowCount(0);//clear table data
populateTable();//method you use to populate your table`

java.lang.NullPointerException error populating JTable from mysql

Im trying to populate JTable with MySql data. Thing is when i run Login class, i receive message "java.SQLException: No value specified for parameter 2" and when i run JTable class I keep receiving java.lang.NullPointerException error. I have three classes : 1-Connection to DB:
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class javaconnect {
Connection conn = null;
public static Connection ConnecrDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb",
"root", "root");
JOptionPane.showMessageDialog(null, "Connected");
return con;
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
return null;
}
}
The second class is login frame:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.*;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JFrameLogIn extends JFrame {
Connection conn =null;
ResultSet rs = null;
PreparedStatement pst = null;
private JPanel contentPane;
private JPasswordField txt_Password;
private JTextField txt_Username;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrameLogIn frame = new JFrameLogIn();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JFrameLogIn() {
conn=javaconnect.ConnecrDB();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 375, 214);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setFont(new Font("Tahoma", Font.BOLD, 13));
lblUsername.setBounds(126, 45, 80, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setFont(new Font("Tahoma", Font.BOLD, 13));
lblPassword.setBounds(126, 82, 69, 14);
contentPane.add(lblPassword);
txt_Password = new JPasswordField();
txt_Password.setBounds(218, 82, 109, 20);
contentPane.add(txt_Password);
txt_Username = new JTextField();
txt_Username.setBounds(216, 43, 111, 20);
contentPane.add(txt_Username);
txt_Username.setColumns(10);
JButton cmd_Login = new JButton("Login");
cmd_Login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sql = "Select * from clients where username=? and password=?";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txt_Username.getText());
pst.setString(1, txt_Password.getText());
rs = pst.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Username and Password are correct");
}
else {
JOptionPane.showMessageDialog(null, "Username and Password are not correct");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
cmd_Login.setBounds(218, 125, 80, 23);
contentPane.add(cmd_Login);
}
}
and the last one is JTable
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.sql.*;
import net.proteanit.sql.DbUtils;
public class JTable1 extends JFrame {
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
private JPanel contentPane;
private JTable table_Admins;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JTable1 frame = new JTable1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JTable1() {
conn = javaconnect.ConnecrDB();
UpdateTable ();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table_Admins = new JTable();
table_Admins.setBounds(30, 28, 378, 54);
contentPane.add(table_Admins);
}
private void UpdateTable () {
try {
String sql = "SELECT *FROM menu";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I am trying to figure out what is the problem but cannot find the solution. Connection works. I would really appreciate your help in fixing this error.
The second parameter in your PreparedStatment is not set. You should replace
pst.setString(1, txt_Password.getText());
with
pst.setString(2, txt_Password.getText());
Edit: Note that JPassword.getText() is deprecated meaning that you should no longer use it. getPassword() is provided in its place:
pst.setString(2, new String(txt_Password.getPassword()));
you can add a check to the code
rs = pst.executeQuery();
if (rs!=null){
if(rs.next()){
JOptionPane.showMessageDialog(null, "Username and Password are correct");
}
else {
JOptionPane.showMessageDialog(null, "Username and Password are not correct");
}
}
And Also in your JTable1 class
if (rs!=null)
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
private void UpdateTable () {
conn = javaconnect.ConnecrDB();// connection and query should be in same place
try {
String sql = "SELECT *FROM menu";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}

Categories

Resources