I'm trying to insert into my database through the actionPerformed method for my button.
But i keep getting "java.lang.NullPointerException" The button press is supposed to insert from the textboxes and send it to the database, but i currently get a java null pointer exception in the actionperformed method. Can you help me?
(You can copy paste the code and run it directly if it would help)
(There is a connection to the Database, so it's not that)
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);
}
}
}
}
Had you checked the not null fields in the database table.Copy the things in the output window.That's the stack trace.
Related
I have a simple program that takes in info for a car sale and enters it in the MySQL DB, everything inserts 100% properly, except the commission integer. It constantly inserts a constant number, never the 'comm' value I have it set to enter. I have the print statement show the correct value but when i check the DB it's not the correct value. I'm not sure if there's a bug on my end or a JDBC thing?
I've entered a simple value of 1, the print statement reads one but the db will always show a value like 1400.
Image links: https://imgur.com/apuKB0C https://imgur.com/Kijl9yL
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.util.Random;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
public class Sale {
Connection con;
Statement st;
int rs;
ResultSet rs1;
ResultSet rs2;
boolean rs3;
JFrame frame5;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sale window = new Sale();
window.frame5.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void connect() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/project", "root", "Alesana14");
st = con.createStatement();
} catch (Exception ex) {
}
}
/**
* Create the application.
*/
public Sale() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame5 = new JFrame();
frame5.setBounds(100, 100, 834, 543);
frame5.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame5.getContentPane().setLayout(null);
JLabel lblCreateSale = new JLabel("Create Sale");
lblCreateSale.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
lblCreateSale.setBounds(385, 113, 110, 44);
frame5.getContentPane().add(lblCreateSale);
JLabel label_1 = new JLabel("Model:");
label_1.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_1.setBounds(264, 252, 77, 16);
frame5.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Make:");
label_2.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_2.setBounds(264, 214, 77, 16);
frame5.getContentPane().add(label_2);
JLabel label_4 = new JLabel("Price:");
label_4.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_4.setBounds(264, 294, 77, 16);
frame5.getContentPane().add(label_4);
JLabel label_5 = new JLabel("Color:");
label_5.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_5.setBounds(264, 336, 77, 16);
frame5.getContentPane().add(label_5);
textField = new JTextField();
textField.setColumns(10);
textField.setBounds(353, 210, 185, 26);
frame5.getContentPane().add(textField);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(353, 248, 185, 26);
frame5.getContentPane().add(textField_1);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(353, 284, 185, 26);
frame5.getContentPane().add(textField_3);
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String id = textField_6.getText().trim();
String make = textField.getText().trim();
String model = textField_1.getText().trim();
String price = textField_3.getText().trim();
String color = textField_4.getText().trim();
String year = textField_5.getText().trim();
String sql = "UPDATE product SET inventory = inventory-1 WHERE make='" + make + "' and model = '"
+ model + "' and color ='" + color + "' and yearMade=" + year + "";
// executeUpdate for insert,delete, and update
PreparedStatement ps;
ps = Connectivity.getConnection().prepareStatement(sql);
rs = ps.executeUpdate();
String sql1 = "UPDATE employee SET commission = commission + (commissionRate*"+price+") WHERE id = "+id+"";
ps = Connectivity.getConnection().prepareStatement(sql1);
rs = ps.executeUpdate();
//inserts into sales
Random rand = new Random();
int random =rand.nextInt(999999);
String sql2 = "SELECT id FROM product WHERE make = '"+make+"' and model = '"+model+"' and color = '"+color+"' and yearMade = '"+year+"'";
st = Connectivity.getConnection().createStatement();
rs2 = st.executeQuery(sql2);
while(rs2.next()) {
int totalPrice = Integer.parseInt(price);
Double comm = totalPrice * .035;
int prodID = rs2.getInt("id");
String sql3 = "INSERT INTO sales VALUES('"+random+"','"+id+"','"+prodID+"','"+1+"','"+totalPrice+"',"+comm+")";
ps = Connectivity.getConnection().prepareStatement(sql3);
rs = ps.executeUpdate();
System.out.println(totalPrice);
System.out.println(comm);
System.out.println(ps);
}
JOptionPane.showMessageDialog(null, "Items Sold!");
}
catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnEnter.setBounds(423, 407, 130, 29);
frame5.getContentPane().add(btnEnter);
JButton button_1 = new JButton("Return to menu");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu men = new Menu();
men.frame2.setVisible(true);
frame5.setVisible(false);
}
});
button_1.setBounds(266, 407, 145, 29);
frame5.getContentPane().add(button_1);
textField_4 = new JTextField();
textField_4.setColumns(10);
textField_4.setBounds(353, 326, 185, 26);
frame5.getContentPane().add(textField_4);
JLabel label_6 = new JLabel("Year:");
label_6.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_6.setBounds(264, 374, 77, 16);
frame5.getContentPane().add(label_6);
textField_5 = new JTextField();
textField_5.setColumns(10);
textField_5.setBounds(353, 364, 185, 26);
frame5.getContentPane().add(textField_5);
JLabel lblEmployeeId = new JLabel("Employee ID:\n\n");
lblEmployeeId.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
lblEmployeeId.setBounds(245, 172, 121, 16);
frame5.getContentPane().add(lblEmployeeId);
textField_6 = new JTextField();
textField_6.setColumns(10);
textField_6.setBounds(353, 169, 185, 26);
frame5.getContentPane().add(textField_6);
JLabel imgLabel = new JLabel(new ImageIcon("/Users/jonathonmoreno/Desktop/Project/src/resize.png"));
imgLabel.setBounds(-11, 0, 845, 521);
frame5.getContentPane().add(imgLabel);
}
}
I made an application that has some TextFields. When I click to search an item it popups JTable that contains a list of items. But the problem is how we can do it. I have tried many times but I failed please help in my project.
this is my code that i have tried
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FocusTraversalPolicy;
import javax.swing.JFrame;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import com.alee.laf.WebLookAndFeel;
import com.toedter.calendar.JDateChooser;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.CardLayout;
import java.awt.Component;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
public class DailySales3 {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField ItemID;
private JTextField ItemName;
private JTextField Stock;
private JTextField Qnty;
private JTextField UnitPrice;
private JTextField Tax;
private JTextField Amount;
private JTextField Discount;
private Connection con;
private String query,auto;
private PreparedStatement PStat;
private ResultSet res;
private DefaultTableModel model,model1;
private JTable table_2;
private JScrollPane scrollPane;
private double AmountGet=0.0,AmountCal=0.0,AmountResult=0.0;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WebLookAndFeel.install();
DailySales3 window = new DailySales3();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public DailySales3() {
initialize();
con=Database.Database();
}
public void AmountCalculate()
{
AmountGet=Double.parseDouble(UnitPrice.getText());
AmountCal=Double.parseDouble(Qnty.getText());
AmountResult=AmountCal*AmountGet;
Amount.setText(Double.toString(AmountResult));
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 1229, 658);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 1213, Short.MAX_VALUE)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
);
panel.setLayout(null);
JLabel label = new JLabel("Bill No");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("Georgia", Font.BOLD, 12));
label.setBounds(10, 11, 73, 35);
panel.add(label);
textField = new JTextField();
textField.setFont(new Font("Georgia", Font.BOLD, 15));
textField.setEditable(false);
textField.setColumns(10);
textField.setBounds(82, 11, 132, 35);
panel.add(textField);
JLabel label_1 = new JLabel("Bill Date");
label_1.setHorizontalAlignment(SwingConstants.CENTER);
label_1.setFont(new Font("Georgia", Font.BOLD, 12));
label_1.setBounds(224, 11, 73, 35);
panel.add(label_1);
JDateChooser dateChooser = new JDateChooser();
dateChooser.setFont(new Font("Georgia", Font.BOLD, 15));
dateChooser.setBounds(296, 11, 132, 35);
panel.add(dateChooser);
JLabel label_2 = new JLabel("Sales Type");
label_2.setHorizontalAlignment(SwingConstants.CENTER);
label_2.setFont(new Font("Georgia", Font.BOLD, 12));
label_2.setBounds(438, 11, 73, 35);
panel.add(label_2);
JComboBox comboBox = new JComboBox();
comboBox.setFont(new Font("Georgia", Font.BOLD, 15));
comboBox.setBounds(524, 10, 190, 35);
panel.add(comboBox);
JLabel label_3 = new JLabel("Customers");
label_3.setHorizontalAlignment(SwingConstants.CENTER);
label_3.setFont(new Font("Georgia", Font.BOLD, 12));
label_3.setBounds(724, 11, 73, 35);
panel.add(label_3);
textField_1 = new JTextField();
textField_1.setFont(new Font("Georgia", Font.BOLD, 15));
textField_1.setColumns(10);
textField_1.setBounds(797, 12, 210, 35);
panel.add(textField_1);
JButton button = new JButton("");
button.setBounds(1016, 12, 38, 35);
panel.add(button);
JPanel panel_1 = new JPanel();
panel_1.setBounds(10, 68, 997, 43);
panel.add(panel_1);
JLabel lblItemId = new JLabel("Item ID");
lblItemId.setHorizontalAlignment(SwingConstants.CENTER);
lblItemId.setPreferredSize(new Dimension(91, 35));
lblItemId.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblItemId);
JLabel lblItemName = new JLabel("Item Name");
lblItemName.setPreferredSize(new Dimension(273, 35));
lblItemName.setHorizontalAlignment(SwingConstants.CENTER);
lblItemName.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblItemName);
JLabel lblStock = new JLabel("Stock");
lblStock.setPreferredSize(new Dimension(86, 35));
lblStock.setHorizontalAlignment(SwingConstants.CENTER);
lblStock.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblStock);
JLabel lblQnty = new JLabel("Qnty");
lblQnty.setPreferredSize(new Dimension(86, 35));
lblQnty.setHorizontalAlignment(SwingConstants.CENTER);
lblQnty.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblQnty);
JLabel lblUnitPrice = new JLabel("Unit Price");
lblUnitPrice.setPreferredSize(new Dimension(123, 35));
lblUnitPrice.setHorizontalAlignment(SwingConstants.CENTER);
lblUnitPrice.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblUnitPrice);
JLabel lblTax = new JLabel("Tax (%)");
lblTax.setPreferredSize(new Dimension(86, 35));
lblTax.setHorizontalAlignment(SwingConstants.CENTER);
lblTax.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblTax);
JLabel lblDiscount = new JLabel("Discount (%)");
lblDiscount.setPreferredSize(new Dimension(86, 35));
lblDiscount.setHorizontalAlignment(SwingConstants.CENTER);
lblDiscount.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblDiscount);
JLabel lblAmount = new JLabel("Amount");
lblAmount.setPreferredSize(new Dimension(123, 35));
lblAmount.setHorizontalAlignment(SwingConstants.CENTER);
lblAmount.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblAmount);
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 112, 997, 43);
panel.add(panel_2);
panel_2.setLayout(null);
ItemID = new JTextField();
ItemID.setBounds(5, 5, 89, 34);
ItemID.setFont(new Font("Georgia", Font.BOLD, 15));
ItemID.setColumns(10);
panel_2.add(ItemID);
ItemName = new JTextField();
ItemName.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(ItemName.getText().equals(""))
{
while(table_2.getRowCount()>0)
{
model.removeRow(0);
}
}
else if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
table_2.requestFocus();
table_2.changeSelection(0, 0, false, false);
}
else
{
try {
while(table_2.getRowCount()>0)
{
model.removeRow(0);
}
query="Select Item_No,Item_Name,Current_Stock,Unit_Price,Tax,Discount from StockEntry where Item_Name like '"+ItemName.getText().trim()+"%'";
PStat=con.prepareStatement(query);
res=PStat.executeQuery();
while(res.next())
{
String ItemNo=res.getString("Item_No");
String ItemName=res.getString("Item_Name");
double CStock=res.getDouble("Current_Stock");
double PRate=res.getDouble("Unit_Price");
double tax=res.getDouble("Tax");
double discount=res.getDouble("Discount");
Object row[]= {ItemNo,ItemName,CStock,PRate,tax,discount};
model.addRow(row);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
});
ItemName.setBounds(98, 5, 276, 34);
ItemName.setFont(new Font("Georgia", Font.BOLD, 15));
ItemName.setColumns(10);
panel_2.add(ItemName);
Stock = new JTextField();
Stock.setBounds(376, 5, 89, 34);
Stock.setFont(new Font("Georgia", Font.BOLD, 15));
Stock.setColumns(10);
panel_2.add(Stock);
Qnty = new JTextField();
Qnty.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
model1=(DefaultTableModel)table.getModel();
String itemno=ItemID.getText();
String itemname=ItemName.getText();
String qnty=Qnty.getText();
String unitprice=UnitPrice.getText();
String tax=Tax.getText();
String discount=Discount.getText();
String amount=Amount.getText();
Object rows[]= {itemno,itemname,qnty,unitprice,tax,discount,amount};
model1.addRow(rows);
}
}
});
Qnty.setBounds(469, 5, 89, 34);
Qnty.setFont(new Font("Georgia", Font.BOLD, 15));
Qnty.getDocument().addDocumentListener(new DocumentListener()
{
#Override
public void changedUpdate(DocumentEvent arg0) {
AmountCalculate();
}
#Override
public void insertUpdate(DocumentEvent arg0) {
AmountCalculate();
}
#Override
public void removeUpdate(DocumentEvent arg0) {
}
});
Qnty.setColumns(10);
panel_2.add(Qnty);
UnitPrice = new JTextField();
UnitPrice.setBounds(561, 5, 122, 34);
UnitPrice.setFont(new Font("Georgia", Font.BOLD, 15));
UnitPrice.setColumns(10);
panel_2.add(UnitPrice);
Tax = new JTextField();
Tax.setBounds(687, 5, 89, 34);
Tax.setFont(new Font("Georgia", Font.BOLD, 15));
Tax.setColumns(10);
panel_2.add(Tax);
Discount = new JTextField();
Discount.setBounds(778, 5, 89, 34);
Discount.setFont(new Font("Georgia", Font.BOLD, 15));
Discount.setColumns(10);
panel_2.add(Discount);
Amount = new JTextField();
Amount.setBounds(869, 5, 122, 34);
Amount.setFont(new Font("Georgia", Font.BOLD, 15));
Amount.setColumns(10);
panel_2.add(Amount);
scrollPane = new JScrollPane();
scrollPane.setBounds(10, 156, 997, 412);
panel.add(scrollPane);
table_2 = new JTable();
table_2.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
try
{
int row=table_2.getSelectedRow();
String TableClicked=(table_2.getModel().getValueAt(row, 0).toString());
query="Select * from StockEntry where Item_No='"+TableClicked+"'";
PStat=con.prepareStatement(query);
res=PStat.executeQuery();
if(res.next())
{
String Itemno=res.getString("Item_No");
ItemID.setText(Itemno);
String itemName=res.getString("Item_Name");
ItemName.setText(itemName);
String PurchaseRate=Double.toString(res.getDouble("Unit_Price"));
UnitPrice.setText(PurchaseRate);
String stock=Double.toString(res.getDouble("Current_Stock"));
Stock.setText(stock);
String tax=Double.toString(res.getDouble("Tax"));
Tax.setText(tax);
String disc=Double.toString(res.getDouble("Discount"));
Discount.setText(disc);
}
}
catch(Exception e1)
{
e1.printStackTrace();
}
finally
{
try
{
PStat.close();
res.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
while(table_2.getRowCount()>0)
{
model.removeRow(0);
}
Qnty.requestFocus();
}
}
});
model=(DefaultTableModel)table_2.getModel();
model.addColumn("Item ID");
model.addColumn("Item Name");
model.addColumn("Qnty");
model.addColumn("Unit Price");
model.addColumn("Tax (%)");
model.addColumn("Discount (%)");
model.addColumn("Amount");
table_2.setRowHeight(30);
table_2.getTableHeader().setFont(new Font("Georgia", Font.BOLD, 14));
table_2.setFont(new Font("Georgia", Font.BOLD, 17));
scrollPane.setViewportView(table_2);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(10, 156, 997, 412);
panel.add(scrollPane_1);
table = new JTable();
model1=(DefaultTableModel)table.getModel();
model1.addColumn("Item ID");
model1.addColumn("Item Name");
model1.addColumn("Qnty");
model1.addColumn("Unit Price");
model1.addColumn("Tax (%)");
model1.addColumn("Discount (%)");
model1.addColumn("Amount");
table.setRowHeight(30);
table.setFont(new Font("Georgia", Font.BOLD, 17));
scrollPane_1.setViewportView(table);
frame.getContentPane().setLayout(groupLayout);
}
}
I'm new to using UCanAccess and Microsoft Access as a database for java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import net.ucanaccess.jdbc.*;
public class Memo extends JFrame implements ActionListener {
private JTextField textField;
private JTextField textField_1;
Connection cn = null;
ResultSet rs = null;
Statement s = null;
public Memo() {
getContentPane().setBackground(Color.DARK_GRAY);
getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(246, 0, 178, 50);
getContentPane().add(textField);
textField.setColumns(10);
JLabel lblNewLabel = new JLabel("Enter bill amount: $");
lblNewLabel.setFont(new Font("Arial Narrow", Font.BOLD, 11));
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(10, 0, 237, 50);
getContentPane().add(lblNewLabel);
JLabel label = new JLabel("Enter water usage amount(l): ");
label.setFont(new Font("Arial Narrow", Font.BOLD, 11));
label.setForeground(Color.WHITE);
label.setBounds(10, 49, 237, 50);
getContentPane().add(label);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(246, 49, 178, 50);
getContentPane().add(textField_1);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection cn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\decx\\Desktop\\Db.accdb");
String sql = "insert into db ('ID', 'WaterUsage', 'Bill') + values ('1', '12', '12')";
s = cn.createStatement();
s.executeUpdate(sql);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
});
btnSubmit.setFont(new Font("Arial Narrow", Font.BOLD, 11));
btnSubmit.setBounds(272, 131, 141, 35);
getContentPane().add(btnSubmit);
}
public static void main(String[] args) throws Exception {
Memo qMemo = new Memo();
qMemo.setSize(500, 350);
qMemo.setVisible(true);
qMemo.setTitle("Tips & Tricks");
qMemo.setDefaultCloseOperation(EXIT_ON_CLOSE);
qMemo.getContentPane().setLayout(null);
}
public void actionPerformed(ActionEvent e) {
}
}
I need to get the code to send data when the submit button is clicked. This is a school project where I have to allow users to enter water usage and bill (water utility bill), so I can display it later.
I have ran the code previously and but errors like "unexpected token" or "user has no privilege or object not found".
There are some notes :
You get this error (unexpected token) because the names of columns and table should not be between two quotes ''
The + operator is not allow in that position of query
Also, only the Strings can be between two quotes not the ints, make sure the type of ID for example is a String, if not you have to remove the two quotes
Read about Prepared Statement to avoid syntax error and to prevent SQL Injection
Look at :
String sql="insert into db ('ID', 'WaterUsage', 'Bill') + values ('1', '12', '12')";
//(1)-----------------------^--^--^----------^--^----^ ^ ^ ^
//(2)___________________________________________________| | |
//(3)_____________________________________________________________| |
That helped me a lot and with the help of my friends i completed my code, for anyone who might need this at any point, i'll be including my code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import net.ucanaccess.jdbc.*;
public class Memo extends JFrame implements ActionListener {
private JTextField textField;
private JTextField textField_1;
Connection cn = null;
ResultSet rs = null;
Statement s = null;
public Memo() {
getContentPane().setBackground(Color.DARK_GRAY);
getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(246, 0, 178, 50);
getContentPane().add(textField);
textField.setColumns(10);
JLabel lblNewLabel = new JLabel("Enter bill amount: $");
lblNewLabel.setFont(new Font("Arial Narrow", Font.BOLD, 11));
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(10, 0, 237, 50);
getContentPane().add(lblNewLabel);
JLabel label = new JLabel("Enter water usage amount(l): ");
label.setFont(new Font("Arial Narrow", Font.BOLD, 11));
label.setForeground(Color.WHITE);
label.setBounds(10, 49, 237, 50);
getContentPane().add(label);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(246, 49, 178, 50);
getContentPane().add(textField_1);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
int num = Integer.parseInt(textField.getText());
int num1 = Integer.parseInt(textField_1.getText());
textField.getText();
textField_1.getText();
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection cn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\DECX\\Desktop\\Db.accdb");
String sql = "insert into db (WaterUsage, Bill) values ('"+num+"', '"+num1+"')";
s = cn.createStatement();
s.executeUpdate(sql);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
});
btnSubmit.setFont(new Font("Arial Narrow", Font.BOLD, 11));
btnSubmit.setBounds(272, 131, 141, 35);
getContentPane().add(btnSubmit);
}
public static void main(String[] args) throws Exception {
Memo qMemo = new Memo();
qMemo.setSize(500, 350);
qMemo.setVisible(true);
qMemo.setTitle("Memo");
qMemo.setDefaultCloseOperation(EXIT_ON_CLOSE);
qMemo.getContentPane().setLayout(null);
}
public void actionPerformed(ActionEvent e) {
}
}
When I try to add some function to get data from jtext field under public void actionPerformed(ActionEvent arg0) My GUI goes blank I have attached the images below I can't figure out what's wrong with it.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Register extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Register frame = new Register();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Register() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblName = new JLabel("Name");
lblName.setBounds(56, 56, 56, 16);
contentPane.add(lblName);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(56, 85, 77, 16);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(56, 114, 56, 16);
contentPane.add(lblPassword);
JLabel lblAge = new JLabel("Age");
lblAge.setBounds(56, 143, 56, 16);
contentPane.add(lblAge);
JLabel lblGender = new JLabel("Gender");
lblGender.setBounds(56, 172, 56, 16);
contentPane.add(lblGender);
textField = new JTextField();
textField.setBounds(130, 53, 116, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(130, 82, 116, 22);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(130, 111, 116, 22);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(130, 140, 116, 22);
contentPane.add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(130, 169, 116, 22);
contentPane.add(textField_4);
textField_4.setColumns(10);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnSubmit.setBounds(169, 215, 97, 25);
contentPane.add(btnSubmit);
lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(330, 56, 56, 16);
contentPane.add(lblNewLabel);
}
}
EDIT 1: Added String name to action just to get name.
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String Name;
}
});
and This happened
GUI went blank:
You're using an absolute layout. Since you can't pack() the window, you need to at least validate() its contents.
Register frame = new Register();
frame.validate();
frame.setVisible(true);
Now you can see the real problem: you picked bounds for lblPassword and lblNewLabel that cut off the text on my computer. You really need to use a layout, maybe like this.
i write a convert temperature code using radiobutton, but when i use actionListener to print the value to a label, it show "Cannot refer to the non-final local variable valueto defined in an enclosing scope"
can some one show me the problem and how to fix it? (also sorry for my English)
the Radiobutton
JRadioButton Cbutton = new JRadioButton("Celsius");
Fbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Fbutton.setBounds(10, 40, 109, 23);
contentPane.add(Cbutton);
JRadioButton Fbutton2 = new JRadioButton("Fahrenheit");
Fbutton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText(String.valueOf(valueto));
}
});
i use this to convert
if(Fbutton.isSelected()&&Cbutton2.isSelected()){
value=F;
valueto=(F-32)/1.8;
}else if(Fbutton.isSelected()&&Kbutton2.isSelected()){
value=F;
valueto=(F+459.67)*5/9;
}else if(Cbutton.isSelected()&&Fbutton2.isSelected()){
value=C;
valueto=C*1.8+32;
}else if(Cbutton.isSelected()&&Kbutton2.isSelected()){
value=C;
valueto=C+273.15;
}else if(Kbutton.isSelected()&&Cbutton2.isSelected()){
value=K;
valueto=K-273.15;
}else if(Kbutton.isSelected()&&Fbutton2.isSelected()){
value=K;
valueto=K*9.5-459.67;
}
Edit : i declare valueto at the bottom of the class
double value = 0;
double valueto = 0;
double F = 0, C = 0, K = 0;
it ask me to add final to "double valueto", but when i add it the valueto in "if" become error
The Whole code
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class CtoKtoF extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CtoKtoF frame = new CtoKtoF();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #return
*/
public CtoKtoF() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 303);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
double value = 0 ;
double valueto = 0;
double F = 0, C = 0, K = 0;
Border border = LineBorder.createGrayLineBorder();//make border for Jlabel
final JLabel label = new JLabel("New label");
label.setFont(new Font("Tahoma", Font.PLAIN, 12));
label.setBounds(10, 228, 220, 22);
label.setBorder(border);
contentPane.add(label);
JLabel lblNewLabel = new JLabel("Convert from");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblNewLabel.setBounds(10, 11, 92, 22);
contentPane.add(lblNewLabel);
JRadioButton Fbutton = new JRadioButton("Fahrenheit");
Fbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Fbutton.setBounds(10, 40, 109, 23);
//Fbutton.setActionCommand("F");
contentPane.add(Fbutton);
JRadioButton Cbutton = new JRadioButton("Celcius");
Cbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Cbutton.setBounds(121, 40, 109, 23);
//Cbutton.setActionCommand("C");
contentPane.add(Cbutton);
JRadioButton Kbutton = new JRadioButton("Kelvin");
Kbutton.setFont(new Font("Tahoma", Font.PLAIN, 12));
Kbutton.setBounds(232, 40, 109, 23);
//Kbutton.setActionCommand("K");
contentPane.add(Kbutton);
JLabel lblEnterNumericTemperature = new JLabel("Enter Numeric Temperature");
lblEnterNumericTemperature.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblEnterNumericTemperature.setBounds(10, 70, 238, 22);
contentPane.add(lblEnterNumericTemperature);
textField = new JTextField();
textField.setFont(new Font("Tahoma", Font.PLAIN, 12));
textField.setBounds(10, 103, 220, 22);
textField.setText(String.valueOf(value));
contentPane.add(textField);
textField.setColumns(10);
JRadioButton Fbutton2 = new JRadioButton("Fahrenheit");
Fbutton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText(String.valueOf(valueto));
}
});
Fbutton2.setFont(new Font("Tahoma", Font.PLAIN, 12));
Fbutton2.setBounds(10, 165, 109, 23);
//Fbutton2.setActionCommand("F2");
contentPane.add(Fbutton2);
JRadioButton Cbutton2 = new JRadioButton("Celcius");
Cbutton2.setFont(new Font("Tahoma", Font.PLAIN, 12));
Cbutton2.setBounds(121, 165, 109, 23);
//Cbutton2.setActionCommand("C2");
contentPane.add(Cbutton2);
JRadioButton Kbutton2 = new JRadioButton("Kelvin");
Kbutton2.setFont(new Font("Tahoma", Font.PLAIN, 12));
Kbutton2.setBounds(232, 165, 109, 23);
//Kbutton2.setActionCommand("K2");
contentPane.add(Kbutton2);
ButtonGroup group1 = new ButtonGroup();
group1.add(Fbutton);
group1.add(Kbutton);
group1.add(Cbutton);
ButtonGroup group2 = new ButtonGroup();
group2.add(Fbutton2);
group2.add(Cbutton2);
group2.add(Kbutton2);
/*Fbutton.addActionListener(this);
Cbutton.addActionListener(this);
Kbutton.addActionListener(this);
Fbutton2.addActionListener(this);
Cbutton2.addActionListener(this);
Kbutton2.addActionListener(this);*/
//boolean checked = Fbutton.getState();
JLabel lblConvertTo = new JLabel("Convert to");
lblConvertTo.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblConvertTo.setBounds(10, 136, 92, 22);
contentPane.add(lblConvertTo);
JLabel lblComparableTemperatureIs = new JLabel("Comparable Temperature is");
lblComparableTemperatureIs.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblComparableTemperatureIs.setBounds(10, 195, 238, 22);
contentPane.add(lblComparableTemperatureIs);
if(Fbutton.isSelected()&&Cbutton2.isSelected()){
value=F;
valueto=(F-32)/1.8;
}else if(Fbutton.isSelected()&&Kbutton2.isSelected()){
value=F;
valueto=(F+459.67)*5/9;
}else if(Cbutton.isSelected()&&Fbutton2.isSelected()){
value=C;
valueto=C*1.8+32;
}else if(Cbutton.isSelected()&&Kbutton2.isSelected()){
value=C;
valueto=C+273.15;
}else if(Kbutton.isSelected()&&Cbutton2.isSelected()){
value=K;
valueto=K-273.15;
}else if(Kbutton.isSelected()&&Fbutton2.isSelected()){
value=K;
valueto=K*9.5-459.67;
}
}
}