I have a problem with my code and it has no error log so I can't see the problem . . .
Current Problem:
Mainclass() is where the main frame is. . . Clicking ADD will open
AddBroker() and clicking ADD in AddBroker() will update databse and jtable
in MainClass(). Database can now be updated but the jtable in MainClass() won't
change until you open it again
This is my main class (other codes were redacted to focus on problem)
public class MainClass extends JFrame {
JButton button_17 = new JButton("ADD");
button_17.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//to call class AddBroker()
AddBroker ab = new AddBroker();
ab.setVisible(true);
}
});}
Then this is the class for AddBroker(). . .
public class AddBroker extends JFrame {
JButton btnAdd = new JButton("ADD");
final Object[] addBrokerrow = new Object[3];
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ButtonCon bcd = new ButtonCon();
DriverTableCon dtcd = new DriverTableCon(); //this is just jtable
MainClass mcd = new MainClass();
String a = brokerBroker.getText();
String b = addBroker.getText();
String c = tinBroker.getText();
addBrokerrow[0] = a;
addBrokerrow[1] = b;
addBrokerrow[2] = c;
dtcd.modelBroker.addRow(addBrokerrow);
bcd.addBrokerCon(a,b,c);
}
});}
And ButtonCon() is where the adding of data is
public class ButtonCon {
Connection con;
Statement st;
ResultSet rs;
StringBuffer results;
String url = "jdbc:ucanaccess://C://DATABASE//NTD.accdb";
public void addBrokerCon(String broker, String add, String tin) {
try {
con = DriverManager.getConnection(url);
String sql = "INSERT INTO brokerT (Broker, Address, Tin_No) VALUES (?,?,?)";
ps = con.prepareStatement(sql);
ps.setString(1, broker);
ps.setString(2, add);
ps.setString(3, tin);
ps.executeUpdate();
ps.close();
con.close();
}
catch (Exception e) {
System.out.print(e.toString());
}
} }
There is no error so I have no idea what is wrong here. Any input would be appreciated :)
So it's been a week and what I did try to solve the problem and what I did is add a "Refresh" button that loads the table again.
You fogot about ps.executeUpdate(); between ps.setString(3, tin); and ps.close();.
And remove all with st it is not necessary.
Related
I would like to know how can I reference a java class in my jFrame form to display data on the jTable. This is a code from my jFrame and I want to know how can I put it in a java class and just reference the class here in the JFrame so I could save space in this JFrame form
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = "select * from description";
if(jComboBox1.getSelectedIndex() == 0)
try{
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable1.removeColumn(jTable1.getColumnModel().getColumn(2));
model.setRowCount(0);
while (rs.next()){
model.addRow(new String[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)});
}
} catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
Something like this?
public class CustomActionHandler {
private JComboBox jComboBox1;
// all the necessary stuff you need for the code to work
CustomActionHandler(JComboBox jComboBox1, etc...) {
this.jComboBox1 = jComboBox1;
// finish passing all the data here
}
public static void JComboActionFollowup() {
// TODO add your handling code here:
String sql = "select * from description";
if(jComboBox1.getSelectedIndex() == 0)
try{
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable1.removeColumn(jTable1.getColumnModel().getColumn(2));
model.setRowCount(0);
while (rs.next()){
model.addRow(new String[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)});
}
} catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
}
and in your JFrame:
private CustomActionHandler actionhandler = new CustomActionHandler(jComboBox1, etc...)
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
actionhandler.JComboActionFollowup();
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
this is my code an di get this error, I don't understand why, I tried multiple times to figure it out what is happening, are you able please to help me. I tried to check the several topic that are around here regarding this but nothing similar found and if I need to do a null check, I am new to this and I don't understand exactly what I need to do
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class JavaCrud {
private JPanel Main;
private JTextField txtName;
private JButton saveButton;
private JButton deleteButton;
private JButton updateButton;
private JTextField textField2;
private JTextField txtPrice;
private JTextField txtQty;
public static void main(String[] args) {
JFrame frame = new JFrame("JavaCrud");
frame.setContentPane(new JavaCrud().Main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public JavaCrud() {
Connect();
saveButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name, price, qty;
name = txtName.getText();
price = txtPrice.getText();
qty = txtQty.getText();
try {
pst = con.prepareStatement("insert into products(pname,price,qty)values(?,?,?)");
pst.setString(1, name);
pst.setString(2, price);
pst.setString(3, qty);
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Addedddddd!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
deleteButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String bid;
bid = textField2.getText();
try {
pst = con.prepareStatement("delete from products where pid = ?");
pst.setString(1, bid);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record Deleteeeeee!!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
textField2.setText("");
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
updateButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String pid,name,price,qty;
name = txtName.getText();
price = txtPrice.getText();
qty = txtQty.getText();
pid = textField2.getText();
try {
pst = con.prepareStatement("update products set pname = ?,price = ?,qty = ? where pid = ?");
pst.setString(1, name);
pst.setString(2, price);
pst.setString(3, qty);
pst.setString(4, pid);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record Updateee!!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
textField2.setText("");
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
}
Connection con;
PreparedStatement pst;
public void Connect(){
try{
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/gbproducts","root","root");
System.out.println("Success");
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
A NullPointerException is thrown because you adding an addActionListener to your button that has not been instantiated.
In your JavaCrud() method you need to instantiate your buttons.
saveButton = new JButton("SAVE");
deleteButton = new JButton("DELETE");
updateButton = new JButton("UPDATE");
You would also need to instantiate your JTextfield because after a user clicks on a button you are trying to getText() from a JTextField that is null.
Also, it is better to implements ActionListener to your class than to addActionListener to every button. It allows for cleaner code and easier debugging.
Here you can read up on ActionListener Interface
I created a login GUI login form and tried to login if the username and password matches with that entered in the database. But, I am unable to login
I could not find any error in the code.
public class Login {
private JTextField nameTextField;
private JButton submitButton;
private JTextField passwordTextField;
private JLabel Message;
private JPanel LoginPanel;
public static void main(String[] args) {
JFrame frame=new JFrame("Login");
frame.setContentPane(new Login().LoginPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(650,500);
frame.setVisible(true);
}
public Login() {
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_db", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from employee");
while (rs.next()) {
if (rs.getString("name").equals(nameTextField.getText()) && rs.getString("password").equals(passwordTextField.getText())) {
Message.setText("Login Success");
}
else {
Message.setText("Failed");
}
}
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
});
}}
If the password and username matches, I want the application to show the message "Login Success"
Currently you're scanning the whole table and in fact check the username/password of the last element in the DB.
I would simply get the (unique) element corresponding to the username entered and verify the password.
Something like this:
PreparedStatement st = con.prepareStatement("SELECT password FROM employee WHERE name = ?");
st.setString(1, nameTextField.getText().trim());
ResultSet rs = st.executeQuery();
if (rs.next() && rs.getString(1).equals(passwordTextField.getText()))
Message.setText("Login Success");
else
Message.setText("Failed");
rs.close();
con.close();
I have this vaadin table which i'm using to display and update records that are being stored in MySQL DB, it all works fine except for updating the table after making a modification or an update, I tried using Table.refreshRowCache() but that wasn't useful
try{
Class.forName("com.mysql.jdbc.Driver");
Core.con = DriverManager.getConnection(Core.db,Core.dbUsername,Core.dbPassword);
java.sql.Statement st = Core.con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery(Core.Show);
while(rs.next()){
table.addItem(new Object[]{rs.getInt(1), rs.getString(2), rs.getDate(3)},rs.getInt(1));
}
}catch(Exception e){
e.printStackTrace();
}
table.addItemClickListener(new ItemClickEvent.ItemClickListener(){
#Override
public void itemClick(ItemClickEvent event) {
Name = new TextField("Name");
Name.setRequired(true);
TextField Name1 = new TextField("Name");
Name1.setVisible(false);
Date = new DateField("Date");
Date.setDateFormat("yyyy-MM-dd");
Date.setRequired(true);
DateField Date1 = new DateField("Date");
Date1.setDateFormat("yyyy-MM-dd");
Date1.setVisible(false);
Id = new TextField();
Id.setVisible(false);
Name.setValue((String) event.getItem().getItemProperty("Name").getValue());
Name1.setValue((String) event.getItem().getItemProperty("Name").getValue());
Date.setValue((Date)event.getItem().getItemProperty("Date").getValue());
Date1.setValue((Date)event.getItem().getItemProperty("Date").getValue());
Save = new Button("Save");
Save.setStyleName("small");
Save.setStyleName("primary");
Save.setSizeUndefined();
Save.addClickListener(new Button.ClickListener(){
#Override
public void buttonClick(ClickEvent event) {
try{
Class.forName("com.mysql.jdbc.Driver");
Core.con = DriverManager.getConnection(Core.db,Core.dbUsername,Core.dbPassword);
Core.stmt = Core.con.prepareStatement(Core.Replace);
Core.statement = Core.con.prepareStatement(Core.ReplaceDate);
Core.stmt.setString(1,Name.getValue().toString());
Core.stmt.setString(2,Name1.getValue().toString());
Core.stmt.setDate(3,new java.sql.Date(Date1.getValue().getTime()));
Core.statement.setDate(1,new java.sql.Date(Date.getValue().getTime()));
Core.statement.setString(2,Name1.getValue().toString());
Core.statement.setDate(3,new java.sql.Date(Date1.getValue().getTime()));
Core.stmt.executeUpdate();
Core.statement.executeUpdate();
Notification.show("done");
Name.setVisible(false);
Date.setVisible(false);
Save.setVisible(false);
Delete.setVisible(false);
}catch(Exception e){
e.printStackTrace();
}
}
});
Delete = new Button("Delete");
Delete.setStyleName("small");
Delete.setStyleName("danger");
Delete.setSizeUndefined();
Delete.addClickListener(new Button.ClickListener(){
#Override
public void buttonClick (ClickEvent ev){
try{
Class.forName("com.mysql.jdbc.Driver");
Core.con = DriverManager.getConnection(Core.db,Core.dbUsername,Core.dbPassword);
Core.stmt = Core.con.prepareStatement(Core.Delete);
Core.stmt.setString(1,Name1.getValue().toString());
Core.stmt.setDate(2,new java.sql.Date(Date1.getValue().getTime()));
Core.stmt.executeUpdate();
Notification.show("done");
Name.setVisible(false);
Date.setVisible(false);
Save.setVisible(false);
Delete.setVisible(false);
}catch(Exception ex){
Notification.show(ex.getMessage());
}
}
});
show.addComponent(Name);
show.addComponent(Date);
Edit.addComponent(Save);
Edit.addComponent(Delete);
show.setSpacing(true);
show.addComponent(Edit);
}
});
As stated in the title I'd apreciate a solution to update the rows after making the modification.
Please see the below codem I am trying to call a Jmenu class after successful log in
Login :
public class Login {
Connection con;
Statement st;
ResultSet rs;
JFrame f = new JFrame ("User Login");
JLabel l = new JLabel ("UserName:");
JLabel l1 = new JLabel ("Password:");
JTextField t = new JTextField (10);
JTextField t1 = new JTextField (10);
JButton b = new JButton ("Login");
public Login ()
{
connect ();
frame ();
}
public void connect ()
{
try
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:Joy_DB";
con = DriverManager.getConnection(db);
st = con.createStatement ();
}
catch (Exception ex)
{
}
}
public void frame ()
{
f.setSize (600,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible (true);
JPanel p = new JPanel ();
p.add (l);
p.add (t);
p.add (l1);
p.add (l);
p.add (t1);
p.add (b);
f.add (p);
b.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e)
{
try
{
String user = t.getText (). trim ();
String pass = t1.getText (). trim ();
String sql = "select User,Password from Table2 where User = '"+user+"' and Password = '"+pass+"'";
rs = st.executeQuery(sql);
int count = 0;
while (rs.next())
{
count = count +1;
}
if (count == 1 )
{
JOptionPane.showMessageDialog(null,"User Found");
//JMenuDemo M = new JMenuDemo ();
}
else if (count > 1)
{
JOptionPane.showMessageDialog(null, "Duplicate User !");
}
else
{
JOptionPane.showMessageDialog (null,"User does not exist");
}
}
catch (Exception ex)
{
}
}
});
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new Login ();
//JMenuDemo M = new JMenuDemo ();
// TODO code application logic here
}
}
How can I call the J menu frame after successful log in by using above codem
Please help
I will send the other class which is Jmenu ia a while
Define a LoginPanel with all the logic required to collect the user details
Create another panel that contains your application components and logic.
Use a JDialog to display the login panel. It will block the execution of the code until the dialog is closed
Based on the state of the LoginPane, you would either (possibly) exit the application (failed login) or continue running the application.
Add application panel to a JFrame and make it visible
See How to make dialogs for more details.
You may also want to use PreparedStatement to access information from the database