replace comboBox value into number when inserted into sql - java

I know how to insert the comboBox value into sql but no idea on how to replace the comboBox value with number in sql.
This is some part of my comboBox coding and process button.
User.java
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBounds(126, 105, 140, 20);
contentPane.add(comboBox_1);
comboBox_1.addItem("RM100-RM200");
comboBox_1.addItem("RM200-RM300");
comboBox_1.addItem("RM300-RM400");
JButton btnNewButton = new JButton("Process");
btnNewButton.setBounds(360, 296, 89, 23);
contentPane.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String a=(String)comboBox.getSelectedItem().toString();
Case ca= new Case();
try {
ca.addPlace(a);
LoginGUI um= new LoginGUI();
um.setVisible(true);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Case.java
public void addPlace( String r) throws Exception{
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Insert into menu(Budget)VALUES (?)";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setString(1,r);
ps.executeUpdate();
connect.close();
ps.close();
}
Let say the user select RM100-RM200, value "1" will be inserted into sql instead of RM100-RM200. Anyone can help?

Java comboboxes contain a getSelectedIndex method.
http://docs.oracle.com/javase/8/docs/api/javax/swing/JComboBox.html#getSelectedIndex--

Have you tested you code?
In your actionPerformed() you have written,
String a = (String) comboBox.getSelectedItem().toString();
The object comboBox is nowhere initialised in the code.
Do you mean comboBox_1 because it is the only object of JcomboBox which you have actually initialised in code.
Also
(String) comboBox.getSelectedItem().toString();
The typecast to String is actually not needed as toString return a String only.

Related

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException ? Please help I don't know what to do [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
this is my code an di get this error, I don't understand why, I tried multiple times to figure it out what is happening, are you able please to help me. I tried to check the several topic that are around here regarding this but nothing similar found and if I need to do a null check, I am new to this and I don't understand exactly what I need to do
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class JavaCrud {
private JPanel Main;
private JTextField txtName;
private JButton saveButton;
private JButton deleteButton;
private JButton updateButton;
private JTextField textField2;
private JTextField txtPrice;
private JTextField txtQty;
public static void main(String[] args) {
JFrame frame = new JFrame("JavaCrud");
frame.setContentPane(new JavaCrud().Main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public JavaCrud() {
Connect();
saveButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name, price, qty;
name = txtName.getText();
price = txtPrice.getText();
qty = txtQty.getText();
try {
pst = con.prepareStatement("insert into products(pname,price,qty)values(?,?,?)");
pst.setString(1, name);
pst.setString(2, price);
pst.setString(3, qty);
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Addedddddd!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
deleteButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String bid;
bid = textField2.getText();
try {
pst = con.prepareStatement("delete from products where pid = ?");
pst.setString(1, bid);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record Deleteeeeee!!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
textField2.setText("");
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
updateButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String pid,name,price,qty;
name = txtName.getText();
price = txtPrice.getText();
qty = txtQty.getText();
pid = textField2.getText();
try {
pst = con.prepareStatement("update products set pname = ?,price = ?,qty = ? where pid = ?");
pst.setString(1, name);
pst.setString(2, price);
pst.setString(3, qty);
pst.setString(4, pid);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record Updateee!!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
textField2.setText("");
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
}
Connection con;
PreparedStatement pst;
public void Connect(){
try{
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/gbproducts","root","root");
System.out.println("Success");
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
A NullPointerException is thrown because you adding an addActionListener to your button that has not been instantiated.
In your JavaCrud() method you need to instantiate your buttons.
saveButton = new JButton("SAVE");
deleteButton = new JButton("DELETE");
updateButton = new JButton("UPDATE");
You would also need to instantiate your JTextfield because after a user clicks on a button you are trying to getText() from a JTextField that is null.
Also, it is better to implements ActionListener to your class than to addActionListener to every button. It allows for cleaner code and easier debugging.
Here you can read up on ActionListener Interface

Deleting data in table (SQLite) through java (Eclipse)

as the title suggests, ive been trying to delete data in a table in my SQLite through the use of a button. I have been able to make it work on another class, but i cant seem to make it work on this specific class which i will show you.
the button is called btnDelete, and the method that loads the database and deletes it is called delete_account.
Button btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
Here's the whole code in the class just in case it is needed:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class AccSettings {
private JFrame frmAccountSett;
private JTextField txtFullname;
private JTextField txtUsername;
private JPasswordField txtPassword;
private int userid;
private String user;
/**
* Create the application.
*/
public AccSettings(String username) {
user=username;
//userid = id;
initialize();
edit_account();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmAccountSett = new JFrame();
frmAccountSett.setTitle("Account Settings");
frmAccountSett.setBounds(100, 100, 450, 300);
frmAccountSett.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAccountSett.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Edit Username:");
lblUsername.setBounds(85, 62, 103, 14);
frmAccountSett.getContentPane().add(lblUsername);
txtUsername = new JTextField();
txtUsername.setBounds(229, 59, 137, 20);
frmAccountSett.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(229, 90, 137, 20);
frmAccountSett.getContentPane().add(txtPassword);
JButton btnConfirm = new JButton("Confirm Changes");
btnConfirm.setBounds(146, 164, 137, 29);
frmAccountSett.getContentPane().add(btnConfirm);
JLabel lblPassword = new JLabel("Edit Password:");
lblPassword.setBounds(85, 93, 103, 14);
frmAccountSett.getContentPane().add(lblPassword);
frmAccountSett.setVisible(true);
JButton btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
btnDelete.setBounds(299, 227, 125, 23);
frmAccountSett.getContentPane().add(btnDelete);
JButton btnBack = new JButton("<< Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frmAccountSett.dispose();
}
});
btnBack.setBounds(10, 227, 103, 23);
frmAccountSett.getContentPane().add(btnBack);
JLabel lblFullname = new JLabel("Edit Fullname:");
lblFullname.setBounds(85, 31, 103, 14);
frmAccountSett.getContentPane().add(lblFullname);
txtFullname = new JTextField();
txtFullname.setColumns(10);
txtFullname.setBounds(229, 28, 137, 20);
frmAccountSett.getContentPane().add(txtFullname);
btnConfirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
update_account();
}
});
}
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
public void update_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
#SuppressWarnings("deprecation")
String query="UPDATE tblUsers SET fullname='" + txtFullname.getText()+"',"
+ "username='" + txtUsername.getText()+"',"
+ "password='" + txtPassword.getText()+"'"
+ "WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Reference successfully updated!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
//load the results
public void edit_account()
{
try {
Connection con; //create a variable for con
Database db = new Database(); //create an instance of database class
con = db.open_connection(); //set con as connection form database class
Statement st;
st = con.createStatement();
//create a statement variable
//create the query that will search the table based on similar terms
String query = "SELECT * FROM tblUsers WHERE userID=" + userid+ "";
//get the resultset of the query (rows)
ResultSet rs = st.executeQuery(query);
if (rs.next())
{
do{
txtFullname.setText(rs.getString(2));
txtUsername.setText(rs.getString(3));
txtPassword.setText(rs.getString(4));
}
while(rs.next());
}
/*
else {
JOptionPane.showMessageDialog(null, "Edit failed");
}
*/
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I believe the problem stems mostly from userID which zephyr has stated. I followed a code from another class(frmEditRef), but that class uses a JScrollPane, which when called from another class (frmMainInterface) looks like this:
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
int x = table.getSelectedRow(); //get the current row
int ans = JOptionPane.showConfirmDialog(null, "Do you want to edit this record?");
if (ans == 0) {
//proceed to edit the transaction
//get the id
String id = String.valueOf(model.getValueAt(x, 0));
new EditRef(user,Integer.valueOf(id));
frmUserRef.dispose();
}
}
});
The class im trying to work with does not use JScrollPane. Therefore the coding to it would be different. Here's how it looks like from frmMainInterface:
btnAccountSett.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String id = ;
new AccSettings(user,Integer.valueOf(id));
}
});
As you can see, i have no idea what to put in after the "String id =".
I hope this explanation can get through you guys. I myself am having difficulty trying to explain something i dont even fully understand.

Populating jTable from database based on a column value entered in same table column

I have a jTable. It has 6 column. I need to enter name in column 1 and once I press enter key the other 5 columns must be populated from database. Can anyone help please?
private void jTable2KeyPressed(java.awt.event.KeyEvent evt) {
{
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
{
// Object s=jTable2.getModel().getValueAt(1, 1);
//System.out.println("Value" +s);
Object Name= jTable2.getModel().getValueAt(1, 1);;
try {
openconn();
PreparedStatement ps;
System.out.println("Val" +Name);
ps = conn.prepareStatement("select * from inventory.addproducts where name='"+Name+"'");
rs= ps.executeQuery();
if(rs.next())
{
String rate=rs.getString(2);
jTable2.getModel().setValueAt(rate, 2, 3);
}
else
{
JOptionPane.showInputDialog("Wrong input");
}
conn.close();
}
catch(Exception ex)
{
}
}}
}
Hope this will make sense how to do it, use DefaultTableModel to populate your JTabel, a simple example, have not tried it out:
private DefaultTableModel model=new DefaultTableModel();
private JTable table=new JTable(model);
private JButton submit =new JButton("Submit");
public void populate(){
submit.addActionListener(e->{model.addRow(new Object[]{textField.getText(),database.getSurname(),database.getAge()});})
}

Db Query not executing on Button Click

I'm having a problem with GUI. When I click on JButton b1, when the text is empty in the JTextField text it does not catch the exception.
The query is executing only once when the button is clicked,if clicked again it throws exception and query is not executing
Code:
public class A extends JFrame{
private JTextField text;
private JButton b1;
private JLabel l1;
private Connection conn;
private Statement state;
private ResultSet set;
String server = "jdbc:mysql://localhost";
String user="tim";
String pass="u";
//query enter in textfield | select * from universty.student where rollno=2
public A() throws ClassNotFoundException, SQLException{
super("Frame");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(server,user,pass);
state = conn.createStatement();
getContentPane().setLayout(null);
text = new JTextField();
text.setBounds(35, 132, 346, 35);
getContentPane().add(text);
l1= new JLabel();
l1.setFont(new Font("Tahoma", Font.PLAIN, 22));
l1.setBounds(35, 305, 384, 27);
getContentPane().add(l1);
b1 = new JButton("Submit");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = text.getText();
set = state.executeQuery(query);
set.next();
String answer = set.getString(2);
l1.setText(answer);
}
catch (Exception e){
JOptionPane.showMessageDialog( null,
e.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE );
return;
}
finally{
try{
set.close();
state.close();
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}});
b1.setBounds(132, 178, 129, 35);
getContentPane().add(b1);
setSize(450,450);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
}
Main Method:
public class Main {
public static void main(String args[]) throws ClassNotFoundException, SQLException{
A obj = new A();
}
}
You should open and close the database connection within your:
actionPerformed()
Since when you call your constructor it opens the db connection and closes it again. When you click the db connection is already closed again
public void actionPerformed(ActionEvent arg0) {
conn = DriverManager.getConnection(server,user,pass);
state = conn.createStatement();
//do query here
set.close();
state.close()
conn.close();
}
At the end of the first click, you close everything with following statement.
finally{
try{
set.close();
state.close();
conn.close();
That's why.
__UPDATE__
I am asked to provide a solution. Actually I have given half of the solution by pin-pointing the problem. But let me elaborate more, since I am asked.
Simple solution is not to close connection or statement or whatever. But this would be a bad solution, as unnecessary resources could be hold active. No need for that.
I do not know your application. So I can not give you a precise answer but rather, I can give you some guide lines and help you find the right answer by yourself.
Hold on to the resources, as long as you need them. And get rid of them as soon as you are done with them. For this case, If it is required user to click on that button and make a change in the database, then do not close connection etc but reuse them. If it is a multi-page application, you can close these resource when user moves to another page. (or activity if it a mobile app).
I hope it makes sense =]
I'm not sure of the purpose of your code but you should try and separate your view logic from your business logic. Also allowing a user to run SQL from a text box and submit button sounds dangerous, but if that's really what you want to do, here is one implementation you could use. Note the DAO here is not a true DAO because of the way you want to execute a query
public class A extends JFrame {
private final JTextField text;
private final JButton b1;
private final JLabel l1;
private AService service;
public A() {
super("Frame");
service = new AServiceImpl(new ADAOJDBCImpl());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
text = new JTextField();
text.setBounds(35, 132, 346, 35);
getContentPane().add(text);
l1= new JLabel();
l1.setFont(new Font("Tahoma", Font.PLAIN, 22));
l1.setBounds(35, 305, 384, 27);
getContentPane().add(l1);
b1 = new JButton("Submit");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String query = text.getText();
try {
String answer = service.executeQuery(query);
l1.setText(answer);
} catch (SQLException e){
JOptionPane.showMessageDialog( null,
e.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE );
return;
}
}});
b1.setBounds(132, 178, 129, 35);
getContentPane().add(b1);
setSize(450,450);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
pack();
setVisible(true);
}
}
public interface AService {
public String executeQuery(String query) throws SQLException;
}
public class AServiceImpl implements AService {
private ADAO dao;
public AServiceImpl(ADAO dao) {
this.dao = doa;
}
#Override
public String executeQuery(String query) throws SQLException {
return dao.executeQuery();
}
}
/**
* Note usually a DAO is specfically for accessing data, NOT
* for executing User defined queries from a GUI text box
* so it would usually have methods such as add, find, delete, update etc.
*/
public interface ADAO {
public String executeQuery(String query) throws SQLException;
}
public class ADAOJDBCImpl implements ADAO {
#Override
public String executeQuery(String query) throws SQLException {
String server = "jdbc:mysql://localhost";
String user="tim";
String pass="u";
String answer = "":
try (Connection conn = DriverManager.getConnection(server,user,pass);
Statement state = conn.createStatement();
ResultSet set = state.executeQuery(query);) {
if(set.next()) {
answer = set.getString(2);
}
}
return answer;
}
}

JTextField Update based on JComboBox Selection

I'm trying to build a form where one can fill in own's own values into a JTextField or rely a preset option which is depending on a selection from a JComboBox.
This is the JCombobox
String[] areas = new String [] {"Own Specifications", "SurveySample", "UK", "London", "Surrey"};
#SuppressWarnings({ "unchecked", "rawtypes" })
final JComboBox<String> selectedArea = new JComboBox(areas);
//selectedArea = new JComboBox<String>();
selectedArea.setModel(new DefaultComboBoxModel<String>(areas));
selectedArea.setBounds(282, 52, 164, 27);
contentPane.add(selectedArea);
And this is the JTextField
tenurePrivateRenters = new JTextField();
tenurePrivateRenters.setHorizontalAlignment(SwingConstants.CENTER);
tenurePrivateRenters.setText("Private Renters");
tenurePrivateRenters.setBounds(58, 213, 134, 28);
contentPane.add(tenurePrivateRenters);
Depending on the JComboBox Selection of the user, in a JTextField, the value is supposed to change, e.g. if Survey Sample is selected the JTextField should chance its value to 10.
I've tried the two following option:
selectedArea.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
Object selectedValue = selectedArea.getSelectedItem();
if(selectedValue.equals("Own Specifications")){
tenurePrivateRenters.setText("10");
System.out.println("Good choice!");
}
}
});
and
selectedArea.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e){
#SuppressWarnings("unchecked")
JComboBox<String> selectedArea = (JComboBox<String>) e.getSource();
String selectedItem = (String) selectedArea.getSelectedItem();
if(selectedItem.equals("Own Specifications")){
tenurePrivateRenters.setText("10");
System.out.println("Good choice!");
}
}
}
);
}
But for both options nothing happens and the value of the JTextField remains on "Private Renters". Any idea's on where I'm going wrong?
In your itemStateChanged method, you have the following:
Object selectedValue = selectedArea.getSelectedItem();
The getSelectedItem method returns an Object. Then, you call that Object's equals method:
if(selectedValue.equals("Own Specifications")){
This will certainly always return false because the Object equals method is comparing an object of type String to an object of type Object.
Instead, if you want to compare selectedValue to a String:
String selectedValue = (String)selectedArea.getSelectedItem();
Then, the if statement should work as expected.
I have tried your code and it worked perfectly. Are you sure you are properly attaching those listeners to combobox BEFORE you try to change its value? Try to attach them right in the constructor to be sure.

Categories