java app querying database returning nullpointerexception - java

I'm having a problem with my code in java. It is supposed to insert data into a database but it's returning a nullpointerexception. Here is my code.
package client;
import java.sql.*;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class AddCon {
private Connection conn;
private JFrame frmAddContract;
private JTextField ContractNo;
private JTextField EngagerName;
private JTextField contNo;
private JTextField month;
private JTextField day;
private JTextField year;
private JTextField tme;
private JTextField cladd;
private JTextField eventadd;
private JTextField textField_fp;
private JTextField refer;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddCon window = new AddCon();
window.frmAddContract.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AddCon() {
try{
//Load database driver and connect
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/KusinaNiKambal","root","1234");
Statement stmt = null;
stmt = conn.createStatement();}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);}
/**
* Initialize the contents of the frame.
*/
initialize();
}
private void initialize() {
frmAddContract = new JFrame();
frmAddContract.setResizable(false);
frmAddContract.setTitle("Add Contract");
frmAddContract.setBounds(100, 100, 450, 640);
frmAddContract.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAddContract.getContentPane().setLayout(null);
ContractNo = new JTextField();
ContractNo.setBounds(38, 32, 152, 20);
frmAddContract.getContentPane().add(ContractNo);
ContractNo.setColumns(10);
JLabel lblContract = new JLabel("Contract #");
lblContract.setBounds(38, 18, 76, 14);
frmAddContract.getContentPane().add(lblContract);
JLabel lblEngager = new JLabel("Engager");
lblEngager.setBounds(38, 63, 48, 14);
frmAddContract.getContentPane().add(lblEngager);
EngagerName = new JTextField();
EngagerName.setBounds(38, 78, 152, 20);
frmAddContract.getContentPane().add(EngagerName);
EngagerName.setColumns(10);
contNo = new JTextField();
contNo.setBounds(38, 128, 152, 20);
frmAddContract.getContentPane().add(contNo);
contNo.setColumns(10);
JLabel lblNewLabel = new JLabel("Contact #");
lblNewLabel.setBounds(38, 109, 86, 14);
frmAddContract.getContentPane().add(lblNewLabel);
month = new JTextField();
month.setBounds(38, 255, 116, 20);
frmAddContract.getContentPane().add(month);
day = new JTextField();
day.setBounds(181, 255, 81, 20);
frmAddContract.getContentPane().add(day);
year = new JTextField();
year.setBounds(294, 255, 86, 20);
frmAddContract.getContentPane().add(year);
year.setColumns(10);
JLabel lblMonth = new JLabel("Month in number format");
lblMonth.setBounds(38, 236, 100, 14);
frmAddContract.getContentPane().add(lblMonth);
JLabel lblDay = new JLabel("Day");
lblDay.setBounds(181, 236, 48, 14);
frmAddContract.getContentPane().add(lblDay);
JLabel lblYear = new JLabel("Year");
lblYear.setBounds(294, 236, 48, 14);
frmAddContract.getContentPane().add(lblYear);
JLabel lblEventDate = new JLabel("Event Date");
lblEventDate.setBounds(38, 222, 76, 14);
frmAddContract.getContentPane().add(lblEventDate);
tme = new JTextField();
tme.setBounds(38, 307, 59, 20);
frmAddContract.getContentPane().add(tme);
tme.setColumns(10);
cladd = new JTextField();
cladd.setBounds(38, 180, 363, 31);
frmAddContract.getContentPane().add(cladd);
cladd.setColumns(10);
JLabel lblAddress = new JLabel("Client Address");
lblAddress.setBounds(38, 159, 98, 14);
frmAddContract.getContentPane().add(lblAddress);
JLabel lblTime = new JLabel("Time");
lblTime.setBounds(38, 286, 60, 14);
frmAddContract.getContentPane().add(lblTime);
eventadd = new JTextField();
eventadd.setBounds(38, 358, 373, 50);
frmAddContract.getContentPane().add(eventadd);
eventadd.setColumns(10);
JLabel lblEventAddress = new JLabel("Event Address");
lblEventAddress.setBounds(38, 338, 116, 14);
frmAddContract.getContentPane().add(lblEventAddress);
textField_fp = new JTextField();
textField_fp.setBounds(38, 454, 276, 20);
frmAddContract.getContentPane().add(textField_fp);
textField_fp.setColumns(10);
JLabel lblFilepathOfContract = new JLabel("Filepath of Contract - the PDF file");
lblFilepathOfContract.setBounds(38, 431, 116, 14);
frmAddContract.getContentPane().add(lblFilepathOfContract);
JButton btnBrowse = new JButton("Browse...");
btnBrowse.setBounds(324, 453, 89, 23);
frmAddContract.getContentPane().add(btnBrowse);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
String filepath = fc.getSelectedFile().getAbsolutePath();
textField_fp.setText(filepath);
}
});
refer = new JTextField();
refer.setBounds(38, 510, 276, 20);
frmAddContract.getContentPane().add(refer);
refer.setColumns(10);
JLabel lblEncodedBy = new JLabel("Referred By");
lblEncodedBy.setBounds(38, 485, 116, 14);
frmAddContract.getContentPane().add(lblEncodedBy);
JButton btnAdd = new JButton("Add");
btnAdd.setBounds(101, 560, 89, 23);
frmAddContract.getContentPane().add(btnAdd);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try{
String cntr = ContractNo.getText();
String en = EngagerName.getText();
String cont = contNo.getText();
String mo = month.getText();
String d = day.getText();
String yr = year.getText();
String dte = yr + "-" + mo + "-" + d;
String cla = cladd.getText();
String tm = tme.getText() + ":00";
String evadd = eventadd.getText();
String filepath = textField_fp.getText();
String ref = refer.getText();
String SQL = "insert into cis "+
"values ('"+cntr+"','"+en+"','"+
cont+"','"+cla+"' '"+dte+"','"+tm+"','"+
evadd+"','"+filepath+"','"+ref+")";
PreparedStatement stmt = conn.prepareStatement(SQL);
ResultSet rs = stmt.executeQuery();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
JButton btnCancel = new JButton("Cancel");
btnCancel.setBounds(225, 560, 89, 23);
frmAddContract.getContentPane().add(btnCancel);
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
frmAddContract.setVisible(false);
}
});
}
}
Sorry, i'm not really that experienced in java programming and this is my first time making a code for querying databases.

You do never initialize your conn instance variable. This will lead to a NullPointerException (at least) in this line:
PreparedStatement stmt = conn.prepareStatement(SQL);
^------------ NEVER INITIALIZED
public class AddCon {
private Connection conn;
...
// constructor
public AddCon() {
try{
//Load database driver and connect
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(<your parameters>);
^----------- MISTAKE
...
In the above code you create a connection, but instead of assigning it to the instance variable you just use a local variable. Replace that line with:
this.conn = DriverManager.getConnection(<your parameters>);
Edit: Please always post the stacktrace in case of exceptions!

Related

I am trying to make a registration form with JAVA, but I can't run my code

I have this code and I can't get it to run. I'm new with JAVA. I was trying to make a login and registration form with JAVA swing, and I finished designing GUI part and I also connected the code with mySQL database. But I don't know why that I can't run the code. I tried debugging it, but can't find the bug. I am using eclipse and I also referenced mySQL jar.
Please let me know, if I'm doing anything wrong. Thank you for the help :)
package login_register_form;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.sql.*;
import javax.swing.JComboBox;
public class RegisterPage implements ActionListener{
JFrame frame;
String[] position = {"Admin", "Manager", "Assistant"};
JTextField firstName;
JTextField lastName;
JTextField userName;
JTextField email;
JPasswordField password;
JPasswordField confirmPW;
JButton registerButton;
JButton cancelButton;
JComboBox jobPosition = new JComboBox(position);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RegisterPage window = new RegisterPage();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application. Calling methods from constructor
*/
public RegisterPage() {
createWindow();
initialize();
actionEvent();
}
/**
* Create a main window
*/
public void createWindow() {
frame = new JFrame();
frame.setTitle("Registration Page");
frame.getContentPane().setBackground(Color.GRAY);
frame.setBounds(100, 100, 1113, 806);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
// panel: orange colored background
JPanel panel = new JPanel();
panel.setBackground(new Color(255,165,0,200));
panel.setBounds(300, 150, 500, 472);
frame.getContentPane().add(panel);
panel.setLayout(null);
// label: scaled background
JLabel background = new JLabel("");
background.setBounds(6, 6, 1100, 772);
ImageIcon icon = new ImageIcon(this.getClass().getResource("/background.jpg"));
Image img = icon.getImage();
Image imgScale = img.getScaledInstance(background.getWidth(), background.getHeight(), Image.SCALE_SMOOTH);
ImageIcon scaledIcon = new ImageIcon(imgScale);
background.setIcon(scaledIcon);
frame.getContentPane().add(background);
// title: "Register Page"
JLabel registerPage = new JLabel("Register Page");
registerPage.setFont(new Font("Lucida Grande", Font.BOLD, 19));
registerPage.setBounds(182, 40, 135, 29);
panel.add(registerPage);
// input: first name
firstName = new JTextField();
firstName.setBounds(145, 76, 210, 32);
panel.add(firstName);
firstName.setColumns(10);
// input: last name
lastName = new JTextField();
lastName.setBounds(145, 120, 210, 32);
panel.add(lastName);
lastName.setColumns(10);
// input: user name
userName = new JTextField();
userName.setBounds(145, 164, 210, 32);
panel.add(userName);
userName.setColumns(10);
// input: password
password = new JPasswordField();
password.setBounds(145, 208, 210, 32);
panel.add(password);
// input: confirm password
confirmPW = new JPasswordField();
confirmPW.setBounds(145, 252, 210, 32);
panel.add(confirmPW);
// input: email
email = new JTextField();
email.setBounds(145, 296, 210, 32);
panel.add(email);
email.setColumns(10);
// input: position
jobPosition.setBounds(145, 340, 210, 32);
panel.add(jobPosition);
// button: cancel
JButton cancelButton = new JButton("Cancel");
cancelButton.setBounds(109, 400, 117, 40);
panel.add(cancelButton);
// button: register
JButton registerButton = new JButton("Register");
registerButton.setBounds(275, 400, 117, 40);
panel.add(registerButton);
// label: first name
JLabel fName = new JLabel("First Name");
fName.setBounds(36, 84, 85, 16);
panel.add(fName);
// label: last name
JLabel lName = new JLabel("Last Name");
lName.setBounds(36, 128, 85, 16);
panel.add(lName);
// label: user name
JLabel uName = new JLabel("User Name");
uName.setBounds(36, 172, 85, 16);
panel.add(uName);
// label: password
JLabel pWord = new JLabel("Password");
pWord.setBounds(36, 216, 85, 16);
panel.add(pWord);
// label: re-password
JLabel cPW = new JLabel("Re-Password");
cPW.setBounds(36, 260, 85, 16);
panel.add(cPW);
// label: email
JLabel eMail = new JLabel("Email");
eMail.setBounds(36, 304, 85, 16);
panel.add(eMail);
// label: position
JLabel position = new JLabel("Position");
position.setBounds(36, 347, 101, 16);
panel.add(position);
}
public void actionEvent() {
// Adding action listener to buttons
registerButton.addActionListener(this);
cancelButton.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==registerButton) {
try {
//Creating Connection Object
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase","root", "root");
//Prepared Statement
PreparedStatement Pstatement=connection.prepareStatement("insert into student value(?,?,?,?,?,?)");
// Specifying the values of it's parameter
Pstatement.setString(1, firstName.getText());
Pstatement.setString(2, lastName.getText());
Pstatement.setString(3, userName.getText());
Pstatement.setString(4, password.getText());
Pstatement.setString(5, confirmPW.getText());
Pstatement.setString(6, email.getText());
Pstatement.setString(7, jobPosition.getSelectedItem().toString());
//Checking for the password match
if (password.getText().equalsIgnoreCase(confirmPW.getText())) {
// Executing query
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Registered Successfully");
} else {
JOptionPane.showMessageDialog(null, "Password did not match");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if (e.getSource()==cancelButton) {
// Clearing Fields
firstName.setText("");
lastName.setText("");
userName.setText("");
password.setText("");
confirmPW.setText("");
email.setText("");
jobPosition.setSelectedItem("Admin");
}
}
}

java.sql.SQLSyntaxErrorException: Table/View 'CUSTOMER' does not exist

I have a prog that takes input from jframe and tries to store that data into a derby embedded database. I have tried to run a simple insert statement to test the database and it gives me the "java.sql.SQLSyntaxErrorException: Table/View 'CUSTOMER' does not exist." Error. What am I doing wrong?`
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Label;
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.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
import java.awt.Button;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JList;
import java.awt.List;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
public class Auto extends javax.swing.JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -5777093322764526515L;
private JPanel contentPane;
private JTextField f_name;
private JTextField l_name;
private JTextField f_name2;
private JTextField l_name2;
private JTextField Age;
private JTextField issuing;
private JTextField liscense_num;
private JTextField rental;
private JTextField return_d;
private JTextField total;
private JTextField Age2;
private JTextField issuing2;
private JTextField liscense_num2;
private JTextField rental2;
private JTextField return_d2;
private JTextField total2;
private JTextField agreement_id;
private Button Submit_button;
private Button Clear_button;
private JButton load_button;
private Button Update_button;
private Button return_car;
private JComboBox<?> car_select, car_select2;
private JRadioButton cc_button;
private JRadioButton cc_button2;
private JRadioButton debit_button;
private JRadioButton debit_button2;
private static String url;
private static Connection myConnection;
private static Statement myStatement;
/**
* Launch the application.
*/
public static void main(String[] args) throws SQLException, ClassNotFoundException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
url = "jdbc:derby:MyDB;create=true";
myConnection = DriverManager.getConnection(url);
myStatement = myConnection.createStatement( );
Auto frame = new Auto();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Auto() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 694, 497);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane Auto_Pane = new JTabbedPane(JTabbedPane.TOP);
Auto_Pane.setBounds(5, 5, 422, 432);
contentPane.add(Auto_Pane);
JPanel New_rent = new JPanel();
Auto_Pane.addTab("New Rental", null, New_rent, null);
New_rent.setLayout(null);
JLabel first_name = new JLabel("First Name: ");
first_name.setBounds(12, 8, 84, 16);
New_rent.add(first_name);
f_name = new JTextField(15);
f_name.setBounds(97, 5, 116, 22);
New_rent.add(f_name);
f_name.setColumns(10);
l_name = new JTextField(15);
l_name.setBounds(97, 40, 116, 22);
l_name.setColumns(10);
New_rent.add(l_name);
JLabel last_name = new JLabel("Last Name: ");
last_name.setBounds(12, 43, 84, 16);
New_rent.add(last_name);
JLabel age = new JLabel("Age: ");
age.setBounds(12, 76, 84, 16);
New_rent.add(age);
Age = new JTextField(2);
Age.setBounds(97, 75, 35, 22);
Age.setColumns(10);
New_rent.add(Age);
JLabel liscense = new JLabel("License #: ");
liscense.setBounds(12, 113, 84, 16);
New_rent.add(liscense);
JLabel issuing_st = new JLabel("Issuing State: ");
issuing_st.setBounds(12, 146, 84, 16);
New_rent.add(issuing_st);
issuing = new JTextField(2);
issuing.setBounds(97, 143, 116, 22);
issuing.setColumns(10);
New_rent.add(issuing);
liscense_num = new JTextField(13);
liscense_num.setBounds(97, 110, 116, 22);
liscense_num.setColumns(10);
New_rent.add(liscense_num);
String[] carStrings = { "Compact", "Midsized", "Standard", "Full Size", "SUV", "Mini Van" };
car_select = new JComboBox<Object>(carStrings);
car_select.setBounds(97, 178, 112, 22);
New_rent.add(car_select);
JLabel car_type = new JLabel("Car Type:");
car_type.setBounds(12, 181, 84, 16);
New_rent.add(car_type);
JLabel rent_date = new JLabel("Rental Date:");
rent_date.setBounds(12, 216, 84, 16);
New_rent.add(rent_date);
rental = new JTextField(10);
rental.setBounds(97, 213, 116, 22);
rental.setColumns(10);
New_rent.add(rental);
JLabel return_date = new JLabel("Return Date:");
return_date.setBounds(12, 251, 84, 16);
New_rent.add(return_date);
return_d = new JTextField(10);
return_d.setBounds(97, 248, 116, 22);
return_d.setColumns(10);
New_rent.add(return_d);
JLabel total_num = new JLabel("Total:");
total_num.setBounds(12, 283, 84, 16);
New_rent.add(total_num);
total = new JTextField(7);
total.setBounds(97, 280, 116, 22);
total.setColumns(10);
New_rent.add(total);
JLabel payment_type = new JLabel("Payment Type:");
payment_type.setBounds(12, 317, 100, 16);
New_rent.add(payment_type);
cc_button = new JRadioButton("Credit Card");
cc_button.setBounds(128, 313, 127, 25);
New_rent.add(cc_button);
debit_button = new JRadioButton("Debit");
debit_button.setBounds(259, 313, 127, 25);
New_rent.add(debit_button);
ButtonGroup group = new ButtonGroup();
group.add(debit_button);
group.add(cc_button);
Submit_button = new Button("Submit");
Submit_button.setBounds(12, 356, 99, 24);
Submit_button.addActionListener(this);
New_rent.add(Submit_button);
Clear_button = new Button("Clear Form");
Clear_button.setBounds(128, 356, 99, 24);
Clear_button.addActionListener(this);
New_rent.add(Clear_button);
JPanel Current_rent = new JPanel();
Auto_Pane.addTab("Current Rental", null, Current_rent, null);
Current_rent.setLayout(null);
load_button = new JButton("Load Current Rental Agreements");
load_button.addActionListener(this);
load_button.setBounds(12, 13, 393, 25);
Current_rent.add(load_button);
List load_list = new List();
load_list.setBounds(12, 54, 393, 229);
Current_rent.add(load_list);
JPanel Rental_ret = new JPanel();
Auto_Pane.addTab("Rental Details", null, Rental_ret, null);
Rental_ret.setLayout(null);
JLabel first_name2 = new JLabel("First Name: ");
first_name2.setBounds(15, 48, 71, 16);
Rental_ret.add(first_name2);
f_name2 = new JTextField(15);
f_name2.setBounds(109, 45, 116, 22);
Rental_ret.add(f_name2);
f_name2.setColumns(10);
l_name2 = new JTextField(15);
l_name2.setBounds(109, 74, 116, 22);
l_name2.setColumns(10);
Rental_ret.add(l_name2);
JLabel last_name2 = new JLabel("Last Name: ");
last_name2.setBounds(15, 77, 69, 16);
Rental_ret.add(last_name2);
Age2 = new JTextField(2);
Age2.setBounds(109, 109, 116, 22);
Age2.setColumns(10);
Rental_ret.add(Age2);
JLabel liscense2 = new JLabel("License #: ");
liscense2.setBounds(15, 141, 64, 16);
Rental_ret.add(liscense2);
JLabel issuing_st2 = new JLabel("Issuing State: ");
issuing_st2.setBounds(15, 170, 83, 16);
Rental_ret.add(issuing_st2);
issuing2 = new JTextField(2);
issuing2.setBounds(109, 167, 116, 22);
issuing2.setColumns(10);
Rental_ret.add(issuing2);
liscense_num2 = new JTextField(13);
liscense_num2.setBounds(109, 138, 116, 22);
liscense_num2.setColumns(10);
Rental_ret.add(liscense_num2);
car_select2 = new JComboBox<Object>(carStrings);
car_select2.setBounds(109, 197, 116, 22);
Rental_ret.add(car_select2);
JLabel car_type2 = new JLabel("Car Type:");
car_type2.setBounds(15, 199, 57, 16);
Rental_ret.add(car_type2);
JLabel rent_date2 = new JLabel("Rental Date:");
rent_date2.setBounds(15, 234, 71, 16);
Rental_ret.add(rent_date2);
JTextField rental2 = new JTextField(10);
rental2.setBounds(109, 231, 116, 22);
rental2.setColumns(10);
Rental_ret.add(rental2);
JLabel return_date2 = new JLabel("Return Date:");
return_date2.setBounds(15, 269, 73, 16);
Rental_ret.add(return_date2);
JTextField return_d2 = new JTextField(10);
return_d2.setColumns(10);
return_d2.setBounds(109, 266, 116, 22);
Rental_ret.add(return_d2);
JLabel total_num2 = new JLabel("Total:");
total_num2.setBounds(15, 298, 34, 16);
Rental_ret.add(total_num2);
JTextField total2 = new JTextField(7);
total2.setColumns(10);
total2.setBounds(109, 295, 116, 22);
Rental_ret.add(total2);
JLabel payment_type2 = new JLabel("Payment Type:");
payment_type2.setBounds(15, 332, 86, 16);
Rental_ret.add(payment_type2);
cc_button2 = new JRadioButton("Credit Card");
cc_button2.setBounds(109, 328, 93, 25);
Rental_ret.add(cc_button2);
debit_button2 = new JRadioButton("Debit");
debit_button2.setBounds(220, 326, 57, 25);
Rental_ret.add(debit_button2);
ButtonGroup group2 = new ButtonGroup();
group2.add(debit_button);
group2.add(cc_button);
JLabel age2 = new JLabel("Age: ");
age2.setBounds(15, 112, 31, 16);
Rental_ret.add(age2);
Update_button = new Button("Update");
Update_button.setBounds(15, 368, 83, 24);
Rental_ret.add(Update_button);
Update_button.addActionListener(this);
JLabel Agreement = new JLabel("Agreement ID: ");
Agreement.setBounds(15, 13, 93, 16);
Rental_ret.add(Agreement);
agreement_id = new JTextField();
agreement_id.setColumns(10);
agreement_id.setBounds(109, 10, 116, 22);
Rental_ret.add(agreement_id);
return_car = new Button("Return Car");
return_car.setBounds(109, 368, 83, 24);
Rental_ret.add(return_car);
return_car.addActionListener(this);
}
public void actionPerformed(ActionEvent action) {
if(action.getSource() == Submit_button){
try {
myStatement.executeUpdate("INSERT INTO Customer (FNAME, LNAME, AGE, LICNUM, STATE, CAR_TYPE, RENTDATE, RETURNDATE, TOTAL, PAYTYPE, RETURNED) VALUES('chen','lee', 40,'S633-433-83-400-0', 'FL', 'C', '2016-04-07', '2016-04-10', 213.47, 'Credit', true)");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(action.getSource() == load_button);
if(action.getSource() == Clear_button);
if(action.getSource() == return_car);
if(action.getSource() == Update_button);
}
}
You need to have the Customers table on your database. Your code insert but don't create the table.
Is necessary to create the table by your code or directly in your DBMS.
Example:
try {
c = DriverManager.getConnection("jdbc...", "user", "pass");
String com = "CREATE TABLE Customers(col1 VARCHAR(20) PRIMARY KEY, coln VARCHAR(50) NOT NULL);";
PreparedStatement st = c.prepareStatement(com);
st.execute();
st.close();
System.out.println("OK!");
}
catch (Exception e) {
e.printStackTrace();
}
Where c is a Connection.
OK I have the Table created under APP. But My INSERT statement does not work, even though the format is correct and query for create table worked from program. The Submit button has action listener so that's not the problem. Why is this statement not working?
try {
myStatement.execute("create table Customer (AgreementID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY(START WITH 1000, INCREMENT BY 1), "
+ "FNAME VARCHAR(25) NOT NULL, LNAME VARCHAR(25) NOT NULL, AGE INTEGER NOT NULL, "
+ "LICNUM VARCHAR(20) NOT NULL, STATE VARCHAR(2) NOT NULL, "
+ "CAR_TYPE VARCHAR(12) NOT NULL, RENTDATE VARCHAR(25) NOT NULL, RETURNDATE VARCHAR(25) NOT NULL, TOTAL DECIMAL(7,2) NOT NULL, "
+ "PAYTYPE VARCHAR(20) NOT NULL, RETURNED BOOLEAN, constraint customer_id_pk primary key (AgreementID))");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
myStatement.execute("create table Customer (AgreementID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY(START WITH 1000, INCREMENT BY 1), "
+ "FNAME VARCHAR(25) NOT NULL, LNAME VARCHAR(25) NOT NULL, AGE INTEGER NOT NULL, "
+ "LICNUM VARCHAR(20) NOT NULL, STATE VARCHAR(2) NOT NULL, "
+ "CAR_TYPE VARCHAR(12) NOT NULL, RENTDATE VARCHAR(25) NOT NULL, RETURNDATE VARCHAR(25) NOT NULL, TOTAL DECIMAL(7,2) NOT NULL, "
+ "PAYTYPE VARCHAR(20) NOT NULL, RETURNED BOOLEAN, constraint customer_id_pk primary key (AgreementID))");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

What is wrong with this Java random software code?

I have made software in Java that generates random number in range. But it don't work. Sorry for strange language and comments. I have three classes: main, for generating and GUI. When I click button to generate it shows 0 on screen. Please help me.
public class glavnaKlasa {
static public int broj;
public static void main(String[] args) {
GUI guiObject = new GUI();
guiObject.mainGUI();
generisanje generisanjeObject = new generisanje();
broj = generisanjeObject.glavno(guiObject.min, guiObject.max);
}
}
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GUI {
private JFrame frmNasumicniBroj;
private JTextField textField;
private JTextField textField_1;
private JLabel lblNasumicniBroj;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void mainGUI() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frmNasumicniBroj.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public int min, max;
private void initialize() {
frmNasumicniBroj = new JFrame();
frmNasumicniBroj.setTitle("Nasumicni broj");
frmNasumicniBroj.getContentPane().setBackground(Color.CYAN);
frmNasumicniBroj.setBounds(100, 100, 400, 300);
frmNasumicniBroj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmNasumicniBroj.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Donja granica: ");
lblNewLabel.setForeground(Color.YELLOW);
lblNewLabel.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblNewLabel.setBounds(10, 11, 154, 14);
frmNasumicniBroj.getContentPane().add(lblNewLabel);
textField = new JTextField();
textField.setBounds(200, 8, 154, 20);
frmNasumicniBroj.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblGornjaGranica = new JLabel("Gornja granica: ");
lblGornjaGranica.setForeground(Color.YELLOW);
lblGornjaGranica.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblGornjaGranica.setBounds(10, 36, 165, 14);
frmNasumicniBroj.getContentPane().add(lblGornjaGranica);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(200, 33, 154, 20);
frmNasumicniBroj.getContentPane().add(textField_1);
lblNasumicniBroj = new JLabel("Nasumicni broj: ");
lblNasumicniBroj.setForeground(Color.YELLOW);
lblNasumicniBroj.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblNasumicniBroj.setBounds(10, 144, 180, 14);
frmNasumicniBroj.getContentPane().add(lblNasumicniBroj);
textField_2 = new JTextField();
textField_2.setEditable(false);
textField_2.setBounds(200, 141, 154, 20);
frmNasumicniBroj.getContentPane().add(textField_2);
textField_2.setColumns(10);
JButton btnNewButton = new JButton("GENERISI");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
min = Integer.parseInt(textField.getText());
max = Integer.parseInt(textField_1.getText());
glavnaKlasa glKlasa = new glavnaKlasa();
String brString = Integer.toString(glKlasa.broj);
textField_2.setText(brString);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 14));
btnNewButton.setBounds(10, 61, 345, 72);
frmNasumicniBroj.getContentPane().add(btnNewButton);
JLabel lblVerzija = new JLabel("Verzija: 1.0");
lblVerzija.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
lblVerzija.setBounds(10, 180, 71, 14);
frmNasumicniBroj.getContentPane().add(lblVerzija);
JLabel label_1 = new JLabel("Autor: Djordje Milanovic");
label_1.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
label_1.setBounds(10, 205, 141, 14);
frmNasumicniBroj.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Copyright: Alfin Informatics");
label_2.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
label_2.setBounds(9, 236, 166, 14);
frmNasumicniBroj.getContentPane().add(label_2);
}}
import java.util.Random;
import javax.swing.JOptionPane;
public class generisanje {
public static int glavno(int min, int max){
if (min >= max) {
JOptionPane.showMessageDialog(null, "Maksimalni broj mora biti veci od minimalnog");
}
Random rnd = new Random();
return rnd.nextInt((max - min) + 1) + min;
}
}
This:
glavnaKlasa glKlasa = new glavnaKlasa();
creates the object with empty constructor, your main will not run there, so broj remains uninitialized.
Actually, you don't need to instantiate this class there, just this:
public void actionPerformed(ActionEvent arg0) {
try{
min = Integer.parseInt(textField.getText());
max = Integer.parseInt(textField_1.getText());
int broj = generisanje.glavno(guiObject.min, guiObject.max);
String brString = Integer.toString(broj);
textField_2.setText(brString);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Also consider working according to Java coding standards ( class name first uppercase and so on, it will be much easier to maintain the code).

Java null pointer exception input to database in phpmyadmin with GUI and MYSQL [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 8 years ago.
Improve this question
I'm trying to add input to my database through the use of my GUI and MYSQL code. But i keep getting "java.lang.NullPointerException" And it probably isn't the last error after that has been fixed.. Anyway. The button press is supposed to take the input from the textboxes that you input, and send it to the database, but it doesn't quite work.
Can you help me? The problem is somewhere in the actionPerformed method
(You can copy paste the code and run it directly if it would help)
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JToolBar;
import javax.swing.JDesktopPane;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JRadioButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import javax.swing.JPasswordField;
import javax.swing.JList;
import javax.swing.JComboBox;
public class MyGuiApplication {
//database globals
private Connection con;
private Statement st;
private ResultSet rs;
//gui globals
private JFrame frame;
private JTextField EmailTextField;
private JTextField FirstNameTextField;
private JTextField LastNameTextField;
private JTextField MobileNumberTextField;
private JLabel lblPassword;
private JLabel lblConfirmPassword;
private JRadioButton MrsMsBTN;
private JRadioButton MrBTN;
private JLabel lblTitle;
private JLabel lblFirstName;
private JLabel lblLastName;
private JLabel lblMobileNumber;
private JLabel lblNewCustomer;
private JLabel lblDeliveryInformation;
private JLabel lblInCaseWe;
private JLabel lblMandatoryField;
private JPasswordField ConfirmPasswordField;
private JPasswordField PasswordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyGuiApplication window = new MyGuiApplication();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyGuiApplication() {
initialize();
DBConnect();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 456, 560);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//KNAPPEN
JButton btnUpdate = new JButton("update");
//ACTION LISTENER - TILFØJ DATA TIL DATABASEN VED TRYK PÅ KNAP
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
try
{
String sql="INSERT INTO customers (Email_Address, Password, User_ID, Title_Mr/Mrs, First_Name, Last_Name, Phone_Number, How_did_you_find_us?, Agree_to_terms_&_conditions, Receive_mails_and_offers?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement=con.prepareStatement(sql);
preparedStatement.setString (1, EmailTextField.getText()); // email addresse
preparedStatement.setString (2, PasswordField.getText()); // Stemme overens med ConfirmPasswordField?
preparedStatement.setInt (3, ((Integer) null)); //user ID primary key auto increment
preparedStatement.setString (4, "Mr"); // Title mrs/mr
preparedStatement.setString (5, FirstNameTextField.getText());
preparedStatement.setString (6, LastNameTextField.getText());
preparedStatement.setString (7, MobileNumberTextField.getText());
preparedStatement.setString (8, null); //dropdown menu, "how did you find us"?
preparedStatement.setBoolean(9, true); // agree to terms
preparedStatement.setBoolean(10, true); // receive email offers from us
preparedStatement.executeUpdate();
} catch (Exception e) {
System.out.print(e);
}
}
});
btnUpdate.setBounds(138, 474, 89, 23);
frame.getContentPane().add(btnUpdate);
EmailTextField = new JTextField();
EmailTextField.setBounds(163, 68, 186, 20);
frame.getContentPane().add(EmailTextField);
EmailTextField.setColumns(10);
FirstNameTextField = new JTextField();
FirstNameTextField.setBounds(163, 241, 186, 20);
frame.getContentPane().add(FirstNameTextField);
FirstNameTextField.setColumns(10);
LastNameTextField = new JTextField();
LastNameTextField.setBounds(163, 286, 186, 20);
frame.getContentPane().add(LastNameTextField);
LastNameTextField.setColumns(10);
MobileNumberTextField = new JTextField();
MobileNumberTextField.setBounds(163, 331, 186, 20);
frame.getContentPane().add(MobileNumberTextField);
MobileNumberTextField.setColumns(10);
JCheckBox TermsConditionsCheckBox = new JCheckBox("Yes, i agree to the Terms and Conditions.*");
TermsConditionsCheckBox.setBounds(115, 418, 266, 23);
frame.getContentPane().add(TermsConditionsCheckBox);
JCheckBox EmailOffersCheckBox = new JCheckBox("Yes, i wish to receiver Email offers from Zalando.");
EmailOffersCheckBox.setBounds(115, 444, 319, 23);
frame.getContentPane().add(EmailOffersCheckBox);
JLabel lblEmailAddress = new JLabel("Email Address*");
lblEmailAddress.setBounds(47, 71, 106, 14);
frame.getContentPane().add(lblEmailAddress);
lblPassword = new JLabel("Password*");
lblPassword.setBounds(65, 112, 88, 14);
frame.getContentPane().add(lblPassword);
lblConfirmPassword = new JLabel("Confirm password*");
lblConfirmPassword.setBounds(25, 143, 128, 14);
frame.getContentPane().add(lblConfirmPassword);
MrsMsBTN = new JRadioButton("Mrs./Ms.");
MrsMsBTN.setSelected(true);
MrsMsBTN.setBounds(138, 211, 76, 23);
frame.getContentPane().add(MrsMsBTN);
MrBTN = new JRadioButton("Mr.");
MrBTN.setBounds(216, 211, 109, 23);
frame.getContentPane().add(MrBTN);
lblTitle = new JLabel("Title*");
lblTitle.setBounds(95, 216, 37, 14);
frame.getContentPane().add(lblTitle);
lblFirstName = new JLabel("First name*");
lblFirstName.setBounds(65, 244, 88, 14);
frame.getContentPane().add(lblFirstName);
lblLastName = new JLabel("Last name*");
lblLastName.setBounds(65, 289, 88, 14);
frame.getContentPane().add(lblLastName);
lblMobileNumber = new JLabel("Mobile Number");
lblMobileNumber.setBounds(47, 334, 106, 14);
frame.getContentPane().add(lblMobileNumber);
lblNewCustomer = new JLabel("New Customer");
lblNewCustomer.setFont(new Font("Tahoma", Font.BOLD, 16));
lblNewCustomer.setBounds(25, 37, 149, 14);
frame.getContentPane().add(lblNewCustomer);
lblDeliveryInformation = new JLabel("Delivery information");
lblDeliveryInformation.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblDeliveryInformation.setBounds(10, 181, 109, 14);
frame.getContentPane().add(lblDeliveryInformation);
lblInCaseWe = new JLabel("In case we need to contact you about your order");
lblInCaseWe.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblInCaseWe.setBounds(163, 362, 251, 14);
frame.getContentPane().add(lblInCaseWe);
lblMandatoryField = new JLabel("* mandatory field");
lblMandatoryField.setFont(new Font("Tahoma", Font.ITALIC, 11));
lblMandatoryField.setBounds(25, 478, 100, 14);
frame.getContentPane().add(lblMandatoryField);
ConfirmPasswordField = new JPasswordField();
ConfirmPasswordField.setBounds(163, 142, 186, 20);
frame.getContentPane().add(ConfirmPasswordField);
PasswordField = new JPasswordField();
PasswordField.setBounds(163, 112, 186, 20);
frame.getContentPane().add(PasswordField);
JComboBox comboBox = new JComboBox();
comboBox.setBounds(163, 391, 186, 20);
//comboBox.add("Facebook.com", comboBox);
frame.getContentPane().add(comboBox);
JLabel lblHowDidYou = new JLabel("How did you find us?*");
//ADD OPTIONS TO WHERE YOU FOUND US
lblHowDidYou.setBounds(25, 394, 128, 14);
frame.getContentPane().add(lblHowDidYou);
}
public void DBConnect(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/zalando", "root","");
st = con.createStatement();
}catch(Exception ex){
System.out.println("Error: " +ex);
}
}
}
}
In most probability you have problem connecting to DB, so your connection object "con" is null hence the
java.lang.NullPointerException
java:119
at PreparedStatement preparedStatement=con.prepareStatement(sql);

JLabel does not show value from another class

I have two GUI classes. When I click a row in JTable in the first user interface, the second interface should display the corresponding values in JLabels.
But the second user interface does not show the values.
Here's my first GUI class:
public class ChequeGUI extends JFrame {
public String chqNo;
public String payName;
public double chkAmount = 10;
public Date chkDate;
JTable guiTable = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"Cheque Number","Payee Name","Cheque Amount","Cheque Date"});
public ChequeGUI() throws SQLException {
guiTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
//guiTable.getTableHeader().getDefaultRenderer();
int row = guiTable.getSelectedRow();
chqNo = (String) guiTable.getValueAt(row,0);
payName = (String) guiTable.getValueAt(row,1);
chkAmount = (Double) guiTable.getValueAt(row,2);
chkDate = (Date) guiTable.getValueAt(row, 3);
try {
PrintChequeGUI pcg = new PrintChequeGUI();
pcg.setTitle("Print Cheque");
pcg.setVisible(true);
System.out.println(chqNo);
System.out.println(payName);
System.out.println(chkAmount);
System.out.println(chkDate);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
guiTable.setModel(model);
add(new JScrollPane(guiTable));
DBConnection connection = new DBConnection();
//Populate Table
ChequeDAOImpl chqdi = new ChequeDAOImpl();
chqdi.setConnection(connection);
List<Cheque> cheques = chqdi.getCheques();
for(Cheque cq : cheques){
model.addRow(new Object[]{cq.getChqNum(), cq.getName(),cq.getAmount(),cq.getDate()});
}
}
}
This is my second GUI class:
public class PrintChequeGUI extends JFrame {
private JPanel contentPane;
private JTextField txtAmount;
/**
* Create the frame.
* #throws SQLException
*/
public PrintChequeGUI() throws SQLException {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 480, 400);
contentPane = new JPanel();
contentPane.setBackground(new Color(176, 224, 230));
contentPane.setForeground(SystemColor.inactiveCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 454, 84);
contentPane.add(panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(220, 220, 220));
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_1.setBounds(10, 106, 454, 198);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Date:");
lblNewLabel_1.setBounds(327, 11, 40, 14);
panel_1.add(lblNewLabel_1);
JLabel lblDate = new JLabel();
lblDate.setBounds(368, 11, 69, 14);
panel_1.add(lblDate);
JLabel lblNewLabel_2 = new JLabel("Payee to the Order of");
lblNewLabel_2.setBounds(10, 50, 125, 14);
panel_1.add(lblNewLabel_2);
JLabel lblName = new JLabel();
lblName.setBounds(134, 50, 214, 14);
panel_1.add(lblName);
JLabel lblRs = new JLabel("Rs.");
lblRs.setBounds(351, 50, 24, 14);
panel_1.add(lblRs);
JLabel lblAmount = new JLabel();
lblAmount.setBounds(375, 50, 69, 14);
panel_1.add(lblAmount);
txtAmount = new JTextField();
txtAmount.setBounds(10, 83, 338, 20);
panel_1.add(txtAmount);
txtAmount.setColumns(10);
JLabel lblRupees = new JLabel("Rupees");
lblRupees.setBounds(351, 86, 46, 14);
panel_1.add(lblRupees);
JLabel lbl = new JLabel("Cheque Number:");
lbl.setBounds(10, 126, 100, 14);
panel_1.add(lbl);
JLabel lblChequeNum = new JLabel();
lblChequeNum.setBounds(115, 126, 46, 14);
panel_1.add(lblChequeNum);
JLabel lblSig = new JLabel("<<Sig>>");
lblSig.setBounds(321, 151, 90, 14);
panel_1.add(lblSig);
JLabel lblSigName = new JLabel("A.B.C.Test Name");
lblSigName.setBounds(311, 176, 100, 14);
panel_1.add(lblSigName);
JPanel panel_2 = new JPanel();
panel_2.setBackground(new Color(220, 220, 220));
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_2.setBounds(10, 315, 454, 40);
contentPane.add(panel_2);
panel_2.setLayout(null);
JButton btnPrint = new JButton("Print");
btnPrint.setBounds(102, 11, 89, 23);
panel_2.add(btnPrint);
JButton btnBack = new JButton("Back");
btnBack.setBounds(263, 11, 89, 23);
panel_2.add(btnBack);
ChequeGUI gui = new ChequeGUI();
lblChequeNum.setText(gui.chqNo);
lblAmount.setText(Double.toString(gui.chkAmount));
lblName.setText(gui.payName);
lblDate.setText(String.valueOf(gui.chkDate));
}
}
This can be solved in many ways:
1.
As I mentioned in my comment, Pass the current instance of ChequeGUI to the constructor of PrintChequeGUI and use that instance instead of creating new one in PrintChequeGUI
PrintChequeGUI pcg = new PrintChequeGUI(this);
and in PrintChequeGUI class
public PrintChequeGUI(ChequeGUI gui) throws SQLException {
(but i think its not a good approach)
2.
For Better option, Pass the selected instance of Cheque to PrintChequeGUI as constructor argument. For this you need to create a TableModel with instance of Cheque.
Sample is given below:
package com.test;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class ChequeGUI extends JFrame {
JTable guiTable = new JTable();
ChequeTableModel model;
public ChequeGUI() throws SQLException {
guiTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// guiTable.getTableHeader().getDefaultRenderer();
int row = guiTable.getSelectedRow();
Cheque c = model.getChequeByRow(row);
try {
PrintChequeGUI pcg = new PrintChequeGUI(c);
pcg.setTitle("Print Cheque");
pcg.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
model = new ChequeTableModel();
guiTable.setModel(model);
add(new JScrollPane(guiTable));
model.loadData();
}
public class ChequeTableModel extends AbstractTableModel {
List<Cheque> dataModel;
String[] columns = { "Cheque Number", "Payee Name", "Cheque Amount",
"Cheque Date" };
public ChequeTableModel() {
super();
dataModel = new ArrayList<Cheque>();
}
#Override
public int getColumnCount() {
return columns.length;
}
#Override
public String getColumnName(int column) {
return columns[column];
}
#Override
public int getRowCount() {
return dataModel.size();
}
#Override
public Object getValueAt(int row, int column) {
Object value = null;
Cheque c = getChequeByRow(row);
switch (column) {
case 0:
value = c.chqNo;
break;
case 1:
value = c.payName;
break;
case 2:
value = c.chkAmount;
break;
case 3:
value = c.chkDate;
break;
default:
break;
}
return value;
}
public Cheque getChequeByRow(int row) {
if (dataModel.size() <= 0)
return null;
if (row < 0)
return null;
return dataModel.get(row);
}
public void loadData() {
/*
*
* //Uncomment this for database connection and load data from
* database; //Please note to disconnect database if not needed
*
*
* DBConnection connection = new DBConnection();
*
* // Populate Table ChequeDAOImpl chqdi = new ChequeDAOImpl();
* chqdi.setConnection(connection); List<Cheque> cheques =
* chqdi.getCheques();
*
* for (Cheque cq : cheques) { model.addRow(new Object[] {
* cq.getChqNum(), cq.getName(), cq.getAmount(), cq.getDate() }); }
*/
for (int i = 0; i < 10; i++) {
Cheque c = new Cheque();
c.chkAmount = i * 1000;
c.chqNo = String.valueOf(i);
c.chkDate = new Date(System.currentTimeMillis());
dataModel.add(c);
}
fireTableRowsInserted(0, dataModel.size());
}
}
public static void main(String[] args) throws SQLException {
ChequeGUI c = new ChequeGUI();
c.pack();
c.setVisible(true);
}
}
Second class
package com.test;
import java.awt.Color;
import java.awt.SystemColor;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class PrintChequeGUI extends JFrame {
private JPanel contentPane;
private JTextField txtAmount;
/**
* Create the frame.
*
* #throws SQLException
*/
public PrintChequeGUI(Cheque cheque) throws SQLException {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 480, 400);
contentPane = new JPanel();
contentPane.setBackground(new Color(176, 224, 230));
contentPane.setForeground(SystemColor.inactiveCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 454, 84);
contentPane.add(panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(220, 220, 220));
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_1.setBounds(10, 106, 454, 198);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Date:");
lblNewLabel_1.setBounds(327, 11, 40, 14);
panel_1.add(lblNewLabel_1);
JLabel lblDate = new JLabel();
lblDate.setBounds(368, 11, 69, 14);
panel_1.add(lblDate);
JLabel lblNewLabel_2 = new JLabel("Payee to the Order of");
lblNewLabel_2.setBounds(10, 50, 125, 14);
panel_1.add(lblNewLabel_2);
JLabel lblName = new JLabel();
lblName.setBounds(134, 50, 214, 14);
panel_1.add(lblName);
JLabel lblRs = new JLabel("Rs.");
lblRs.setBounds(351, 50, 24, 14);
panel_1.add(lblRs);
JLabel lblAmount = new JLabel();
lblAmount.setBounds(375, 50, 69, 14);
panel_1.add(lblAmount);
txtAmount = new JTextField();
txtAmount.setBounds(10, 83, 338, 20);
panel_1.add(txtAmount);
txtAmount.setColumns(10);
JLabel lblRupees = new JLabel("Rupees");
lblRupees.setBounds(351, 86, 46, 14);
panel_1.add(lblRupees);
JLabel lbl = new JLabel("Cheque Number:");
lbl.setBounds(10, 126, 100, 14);
panel_1.add(lbl);
JLabel lblChequeNum = new JLabel();
lblChequeNum.setBounds(115, 126, 46, 14);
panel_1.add(lblChequeNum);
JLabel lblSig = new JLabel("<<Sig>>");
lblSig.setBounds(321, 151, 90, 14);
panel_1.add(lblSig);
JLabel lblSigName = new JLabel("A.B.C.Test Name");
lblSigName.setBounds(311, 176, 100, 14);
panel_1.add(lblSigName);
JPanel panel_2 = new JPanel();
panel_2.setBackground(new Color(220, 220, 220));
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_2.setBounds(10, 315, 454, 40);
contentPane.add(panel_2);
panel_2.setLayout(null);
JButton btnPrint = new JButton("Print");
btnPrint.setBounds(102, 11, 89, 23);
panel_2.add(btnPrint);
JButton btnBack = new JButton("Back");
btnBack.setBounds(263, 11, 89, 23);
panel_2.add(btnBack);
// ChequeGUI gui = new ChequeGUI();
lblChequeNum.setText(cheque.chqNo);
lblAmount.setText(Double.toString(cheque.chkAmount));
lblName.setText(cheque.payName);
lblDate.setText(String.valueOf(cheque.chkDate));
}
}
The Cheque class you already used to get details from database

Categories