two comboboxes related to each other [duplicate] - java

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();
}
}

Related

How to insert to database from combo box?

I'm just trying to make some combo box with value from database and I can choose it and insert it to database, but I had some error message. How to resolve that?
Here my code:
private void btnInputDataProdukActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = "insert into tb_produk (produk_kat_id,produk_nm,produk_gndre,produk_size,produk_hrg) values (?,?,?,?,?)";
try {
PreparedStatement stat = conn.prepareStatement(sql);
stat.setString(1, txtNamaProduk.toString());
String valueKat = cbKatProduk.getSelectedItem().toString();
stat.setString(2, valueKat);
String valueGender = cbGender.getSelectedItem().toString();
stat.setString(3, valueGender);
stat.setString(4, txtUkuran.toString());
stat.setString(5, txtHarga.toString());
stat.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Berhasil Disimpan");
kosong();
dataTable();
lebarKolom();
txtNamaProduk.requestFocus();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Data Gagal Disimpan" + e);
}
}
The combo box with value from DB
public void tampil_combo(){
String sql = "select kat_id from tb_kategori";
try {
java.sql.Statement stat = conn.createStatement();
ResultSet res = stat.executeQuery(sql);
while (res.next()) {
Object[] ob = new Object[3];
ob[0]=res.getString(1);
cbKatProduk.addItem((String) ob[0]);
}
res.close();stat.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
produkt_kat_id is defined as an int in your database. But with
stat.setString(1, txtNamaProduk.toString());
you are setting a string. Also note that you are calling toString() on the combo box and not the selected value.
So you need to convert the selected value into an integer:
stat.setString(1, Integer.parseInt(txtNamaProduk.getSelectedItem()));
You would still need to add some error handling in case txtNamaProduk.getSelectedItem() returns null or in case the combo box can also contain other values than integers.
You will also need to change your code for the other fields that are defined as integers in the database.

JComboBox ExecuteQuery selecting Items error

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){
}
}
}

Retrieving data from database and increment by one

I am trying to retrieve a data (ID No.) from a database (MySQL) and add it by one. However, when I try to put this code below, when I try to build it, the form doesn't show up. But when I try to remove the Connection cn line, the form with finally show up. I had another project with this code it it worked perfectly fine. I'm not sure why its not working on this one.
public Abstract() throws Exception {
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
initComponents();
Statement st = null;
ResultSet rs;
try {
String sql = "SELECT ID from bidding_abstractofprices";
st = cn.prepareStatement(sql);
rs = st.executeQuery(sql);
while(rs.next()){
int id = Integer.parseInt(rs.getString("ID")) + 1;
lblTransacID.setText(String.valueOf(id));
}
}catch (Exception ex){
}
}
What it looks like you are trying to do is to get the ID field value from the last record contained within the bidding_abstractofprices Table contained within your Database and then increment that ID value by one (please correct me if I'm wrong). I don't care why but I can easily assume. Here is how I might do it:
public Abstract() throws Exception {
// Allow all your components to initialize first.
initComponents();
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
Statement st = null;
ResultSet rs;
try {
String sql = "SELECT * FROM bidding_abstractofprices ORDER BY ID DESC LIMIT 1;";
st = cn.prepareStatement(sql);
rs = st.executeQuery(sql);
int id = 0;
while(rs.next()){
id = rs.getInt("ID") + 1;
}
lblTransacID.setText(String.valueOf(id));
rs.close();
st.close();
cn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}

MySQL table values in JComboBox

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));}

java database connectivity: jdbc

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)

Categories