I designed a swing interface with MySQL table. I put two comboboxes in a manner when the 1st combobox value is selected (Brand Name), the second combobox values (available items under thise selected brand) will be loaded via a mysql query. My code is...
try{
String url = "jdbc:mysql://localhost:3306/databasename";
String login = "root"; String password = ""; Connection con = DriverManager.getConnection(url, login, password);
try{
comboBox1 = new JComboBox(); comboBox1.setEditable(false);
comboBox1.addItem("- - -");
Statement stmt1=null;
String query1 = "SELECT brand FROM brands";
stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery(query1);
while(rs1.next()) {comboBox1.addItem(rs1.getString(1));}
comboBox2 = new JComboBox(); comboBox2.setEditable(false);
comboBox1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
String comboBox1Selected=comboBox1.getSelectedItem().toString();
try{
Statement stmt2=null;
String query2 = "SELECT item FROM "+comboBox1Selected+"";
stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
while(rs2.next()) {comboBox2.addItem(rs2.getString(1));}
}
catch (SQLException ex1) {JOptionPane.showMessageDialog(null,"Failed to Item-List..!"); ex1.printStackTrace(); return;}
}
});
}
catch (SQLException ex2) {JOptionPane.showMessageDialog(null,"Failed to Brand-List..!"); ex2.printStackTrace(); return;}
}
catch (SQLException ex3) {ex3.printStackTrace(); JOptionPane.showMessageDialog(null,"Unable to Connect..!"); return;}
The problem is, eventhough the comboboxes are functioning correctly, if I select another choice from 1st combobox, the second combobox doesn't avoid the "older values" (they appears with the newer values).
What might be the reason..? Anyone could explain..?
Thanks in advance.
Call comboBox2.removeAllItems() before adding the new items here while(rs2.next()) {comboBox2.addItem(rs2.getString(1));}
Related
I have 3 jComboBox. The first one is for the Room Type. When I select Room Type on the first jComboBox it must show in the second jComboBox all the available room, but when I select one of the Room Type, an error pops u.p
Here is the code for actionperformed on the first jComboBox
first jComboBox actionperformed*
if(jComboBox13.getSelectedItem().toString().equals("SELECT")){
}else{
try{
String like = jComboBox13.getSelectedItem().toString();
String sql = "Select * From Room_Master\n" +
"inner join Room_Type on Room_Master.Room_Type_ID=Room_Type.Room_Type_ID\n" +
"where Room_Type = '"+like+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jComboBox14.removeAllItems();
jComboBox14.addItem("SELECT");
while(rs.next()){
String add1 = rs.getString("Room_No.");
jComboBox14.addItem(add1);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
}
second jComboBox actionperformed
if(jComboBox14.getSelectedItem().toString().equals("SELECT") | jComboBox14.getSelectedItem().toString().isEmpty()){
}else{
try{
String like = jComboBox14.getSelectedItem().toString();
String sql = "Select * from Bed_Master\n" +
"inner join Room_Master on Bed_Master.Room_ID=Room_Master.Room_ID\n" +
"where [Room_No.] = '"+like+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jComboBox15.removeAllItems();
jComboBox15.addItem("SELECT");
while(rs.next()){
String add1 = rs.getString("Bed_No.");
jComboBox15.addItem(add1);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
}
but after i select another Room type it will work
i tried to remove "combobox.removeAllItems();"
but it will keep addding all the items in the jCombobox
almost 1 week trying to figure it out can someone help please
When you call removeAllItems it fires the actionListener for jComoboBox14
and at this stage it will not have any Items so getSelected will return NULL
change your if to
if(jComboBox14.getItemCount() > 0 && (jComboBox14.getSelectedItem().toString().equals("SELECT") |
jComboBox14.getSelectedItem().toString().isEmpty())){
First of all. You should give your objects variables an useful name:
Ex: jComboBox13 --> JComboBox comboRoomsType = new JComboBox(); or whatever name you prefer.
Then, it would be nice to see all the code involved. I can't see where you initialize the ResultSet or PreparedStatement;
I GUESS the NullPointer comes from the select statement, when trying to retrieve the values.
if(jComboBox13.getSelectedItem().toString().equals("SELECT")){
}else{
try{
String like = jComboBox13.getSelectedItem().toString();
String sql = "Select * From Room_Master RM " +
"inner join Room_Type RT on RM.Room_Type_ID=RT.Room_Type_ID "
+"where Room_Type = '"+like+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jComboBox14.removeAllItems();
jComboBox14.addItem("SELECT");
//you can also check if there are values first.
while(rs.hasNext()){
rs.next();
String add1 = rs.getString("Room_No");
//You can also use
//String add1 = rs.getInt(number of column of <Room_No> );
jComboBox14.addItem(add1);
}
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
}
I want to remove the data in database from jtable. I have 1 jTextField and 1 jButton. So when i click this selected row in table, the primary key wont set in my jTextField.
Is it possible to remove the data in database from jtable without jTextField and just a button?
Heres my code
try {
int row = table.getSelectedRow();
String id_ = (table.getModel().getValueAt(row, 1)).toString();
String sql ="SELECT id FROM 'mycredentials.sales' WHERE id= "+id_+"'";
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
PreparedStatement pst = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
jFrame_removeP.setText(rs.getString("id"));
}
} catch (SQLException e1) {
System.err.println(e1);
}
Random id number appears in my jTextField. And my table code is:
String name = jFrame_pName.getText().trim();
String price = jFrame_pPrice.getText().trim();
String quantity = jFrame_quantity.getText().trim();
String total = jFrame_total.getText().trim();
String st[] = {name, price, quantity, total};
model.addRow(st);
jFrame_gTotal.setText(Integer.toString(getSum()));
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
Statement s = (Statement) connection.createStatement();
String sql = "INSERT INTO mycredentials.sales (name, price, quantity, total) VALUES ('"+jFrame_pName.getText()+"', '" + jFrame_pPrice.getText() + "','"+jFrame_quantity.getText()+"','"+jFrame_total.getText()+"')";
s.executeUpdate(sql);
} catch (SQLException e1) {
System.err.println(e1);
}
And my remove button is:
DefaultTableModel model1 = (DefaultTableModel) table_1.getModel();
int selectedRowIndex = table_1.getSelectedRow();
model1.removeRow(selectedRowIndex);
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
Statement ps = (Statement) connection.createStatement();
String sql = "DELETE from mycredentials.sales where id ='" + jFrame_removeP.getText() + "'";
ps.executeUpdate(sql);
} catch (Exception ex) {
System.err.println(ex);
}
Do you mean like this? I didn't get exactly what you needed. Hope this helps.
private void deleteBtnActionPerformed(java.awt.event.ActionEvent evt) {
String deleteQuery = "DELETE FROM SAMPLE WHERE USER_ID = ?";
try (Connection myCon = DBUtilities.getConnection(DBType.JDBC);
PreparedStatement myPs = myCon.prepareStatement(deleteQuery);){
myPs.setInt(1,userID);
myPs.executeUpdate();
JOptionPane.showMessageDialog(null,"Records deleted");
}//end of try
catch (SQLException ex) {
DBUtilities.processException(ex);
}//end of catch
}
After search a record. You just click a record in the Jtable you want to delete. And just hit the Delete Button simple as that.
Just use a refresh method here if you want to remove the selected row. Fix your statement much better if you use Prepared Statement than Statements to avoid SQL injection.
i want to use the string input in textfield in JFrame form as a part of my sql query in java.
For example if i input a name in textfield, i want the sql query to use that name and give the relevant data and not the data of entire table. Like "select * from *table_name* where name = *textfield_input* ;"
following is the code that i'm using to get the data of the entire table.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)p1.getModel();
try{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ritick","root", "iit2012054");
Statement st = con.createStatement();
String query = "select * from student;";
ResultSet rs = st.executeQuery(query);
while(rs.next()){
String d1 = rs.getString("roll_no");
String d2 = rs.getString("name");
String d3 = rs.getString("dept");
String d4 = rs.getString("cgpa");
model.addRow(new Object[]{d1,d2,d3,d4});
}
rs.close();
st.close();
con.close();
}
catch (Exception e){
JOptionPane.showMessageDialog(this, "error in connectivity !");
}
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)p2.getModel();
try{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ritick","root", "iit2012054");
Statement st = con.createStatement();
String query = "show databases;";
ResultSet rs = st.executeQuery(query);
while(rs.next()){
String d1 = rs.getString("database");
model.addRow(new Object[]{d1});
}
rs.close();
st.close();
con.close();
}
catch (Exception e){
JOptionPane.showMessageDialog(this, "error in connectivity !");
}
}
This might help Try to use the PreparedStatement so that
Query is "select * from student where name = ?"
From the statement setString(1, String)
This question already has answers here:
Dynamic JComboBoxes
(2 answers)
Closed 8 years ago.
I have two comboboxes ... First one shows the cities of hotels and the second one shows tha hotels name based on the city selected in first combo box. First Combobox is working correctly. second one shows is only for the first selected city. it does not make changes to itself after changing the city in first combo box ! what do I have to add to this code in order to be able to see changes in second combobox by changing the first combobox.
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String City_Selected = jComboBox1.getSelectedItem().toString();
String select_HN = "select name from tbl_Hotel where city = '"+City_Selected+"';";
ResultSet rs = stat.executeQuery(select_HN);
while (rs.next())
{
String hotel_name = rs.getString("name");
// jLabel3.setText(hotel_name);
jComboBox2.addItem(hotel_name);
}//end while
rs.close();
stat.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
Like this ?
jComboBox1.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
jComboBox2.removeAllItems();
fillComboBoxes();
}
});
private void fillComboBoxes(){
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String City_Selected = jComboBox1.getSelectedItem().toString();
String select_HN = "select name from tbl_Hotel where city = '"+City_Selected+"';";
ResultSet rs = stat.executeQuery(select_HN);
while (rs.next())
{
String hotel_name = rs.getString("name");
// jLabel3.setText(hotel_name);
jComboBox2.addItem(hotel_name);
}//end while
rs.close();
stat.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I've been at this for awhile and have tried different examples (including a few that I found here), and tried to adapt them to what I need.
I am trying to use a DB query in a servlet to populate a combo box in the resulting html form that is created. While it all compiles and the page pops up with a combobox, there is nothing in the box to choose from, which tells me that something is wrong with how I am passing variables.
I've basically narrowed my methods down to two, but get the same results from both.
Can someone have a look-see and give me a clue?
out.print(`"<tr><td>SoldWhich Home ID: `</td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
ArrayList<String> soldWhich = new ArrayList<String>();
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String[])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
And the other method:
out.print(`"<tr><td>SoldWhich Home ID: </td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try{
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home ORDER BY home_id";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
soldWhich.add(rs1.getString(1));
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String [])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
Where are you setting "home_id" request attribute and why are you even setting it? I think you should take out the following line of code and see if it works. Modify your code to this.
List<String> soldWhich = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}
I think you are not actually getting values (sh) in the "for(String sh : soldWhich)" loop. Can you try printing the values in a simple table just to see if you actually get data? Also why aren't you using jstl to perform this task? And your catch block does not log any errors either in case you are actually getting some sort of errors that will go unnoticed.