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.
Related
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`
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);
}
}
I'm designing a database that can be accessed through a GUI, I have three classes Main, Database and GUI, When I run the main I get an error and the GUI closes followed by a brief error message which I cannot read, not sure where this is going wrong as i believe it can be a number of issues. Thanks for all your help :)
Here is my main class
public class MainApplication {
#SuppressWarnings("unused")
public static void main(String[] args) {
VideoStoreGUI window = new VideoStoreGUI();
}
}
My Database Class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import javax.swing.JOptionPane;
#SuppressWarnings("unused")
public class DataBase {
static Connection con = null;
static Statement stmt = null;
static ResultSet rs = null;
static Scanner in = new Scanner(System.in);
public void close_connection() {
try
{
con.close();
System.out.println("Database Connections Succesully Closed.");
}
catch (SQLException sqle)
{
System.out.println("Error: failed to close the database");
}
}
public static void addMember(int member_id, String name, String address) // Adding a Member to the Database.
{
try {
String str = "INSERT INTO members (member_id, name, address) values(" + member_id + ", '" + name + "', '"
+ address + "');";
int rows = stmt.executeUpdate(str);
System.out.println("Success in adding member");
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error: Could not add member");
}
}
public static void initialize_database() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/videostore";
con = DriverManager.getConnection(url, "root", "admin");
stmt = con.createStatement();
} catch (Exception e) {
System.out.println("Error: Failed to connect to database\n" + e.getMessage());
}
}
public DataBase()
{
initialize_database();
}
}
and my GUI class:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JMenuBar;
public class VideoStoreGUI extends JFrame {
private JFrame frame;
DataBase my_database;
private JPanel contentPane;
private JTextField textMemberID;
private JTextField textMemberName;
private JTextField textMemberAddress;
/**
* Create the frame.
*/
public VideoStoreGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 400);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 31, 232, 240);
contentPane.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("Members", null, panel, null);
panel.setLayout(null);
JLabel labelMemberID = new JLabel("Members ID");
labelMemberID.setBounds(10, 11, 85, 14);
panel.add(labelMemberID);
JLabel labelMemberName = new JLabel("Members Name");
labelMemberName.setBounds(10, 36, 85, 14);
panel.add(labelMemberName);
JLabel labelMemberAddress = new JLabel("Members Address");
labelMemberAddress.setBounds(10, 61, 85, 14);
panel.add(labelMemberAddress);
textMemberID = new JTextField();
textMemberID.setBounds(131, 8, 86, 20);
panel.add(textMemberID);
textMemberID.setColumns(10);
textMemberName = new JTextField();
textMemberName.setColumns(10);
textMemberName.setBounds(131, 33, 86, 20);
panel.add(textMemberName);
textMemberAddress = new JTextField();
textMemberAddress.setColumns(10);
textMemberAddress.setBounds(131, 58, 86, 20);
panel.add(textMemberAddress);
JButton buttonAddMember = new JButton("Add Member");
buttonAddMember.setBounds(10, 86, 102, 23);
panel.add(buttonAddMember);
JButton buttonRemoveMember = new JButton("Add Member");
buttonRemoveMember.setBounds(115, 86, 102, 23);
panel.add(buttonRemoveMember);
JButton buttonSearchMember = new JButton("Add Member");
buttonSearchMember.setBounds(66, 120, 102, 23);
panel.add(buttonSearchMember);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("Products", null, panel_1, null);
}
}
I see only one place where you can get popup. You can keep it if you like but add system output and be sure about your message:
catch (SQLException sqle) {
System.out.writeln("Exception:"+sqle);
JOptionPane.showMessageDialog(null, "Error: Could not add member");
}
Based on place of this message I think you have wrong sql or database. I would suggest that you print your sql and results of it too.
The main reason this was not working for me was because I had removed setVisable(true) from the GUI and forgot to add it back to the method, I was then receiving an Error "AWT-EventQueue-0" this was to do with the way my database connection was set up, removing and adding the JDBC driver again resolved this.
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();
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();