3.3 Develop a program to present a set of choice for user to select a product and display the price of product.

Product Table


and insert the following data

    insert into product values(01,'Laptop',35000);
    insert into product values(02,'Desktop',30000);
    insert into product values(03,'Keyboard',700);
    insert into product values(04,'Mouse',500);


ProductList.java
package prac3;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class ProductList extends JFrame implements ItemListener
{
JComboBox comboProductList;
JLabel lblID,lblIDValue,lblPrice,lblPriceValue;
public String names[]={"Choose..","Desktop","Laptop","KeyBoard","Mouse"};

DataDB db=new DataDB();

JPanel p1,p2;

ProductList()
{
setLayout(new FlowLayout());
p1=new JPanel();
comboProductList=new JComboBox(names);
p1.add(comboProductList);

p2=new JPanel();
lblID=new JLabel("ID: ");
lblIDValue=new JLabel("");
lblPrice=new JLabel(" Price: ");
lblPriceValue=new JLabel("");

p2.add(lblID);
p2.add(lblIDValue);
p2.add(lblPrice);
p2.add(lblPriceValue);

comboProductList.addItemListener(this);

add(p1);
add(p2);

setSize(500,230);
setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);


}
/////////////////////////////////////////////////////////////////////////////////////o
public void itemStateChanged(ItemEvent ie)
{
String Name=(String)comboProductList.getItemAt(comboProductList.getSelectedIndex());

try{
db.getData(Name);
lblIDValue.setText(String.valueOf(DataDB.id));
lblPriceValue.setText(String.valueOf(DataDB.p_price));
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args) {
new ProductList();
}
}

DriverClass.java
package prac3;

public class DriverClass{
public String Driver="com.mysql.cj.jdbc.Driver";
public String UserName="root";
public String password="";
public String Path="jdbc:mysql://localhost/test";
}

DataDB.java
package prac3;

import java.sql.*;
public class DataDB{
public static int id=0;
public static int p_price=0;
DriverClass d=new DriverClass();
public void getData(String Name)throws Exception
{
Class.forName(d.Driver);
Connection con=DriverManager.getConnection(d.Path,d.UserName,d.password);
System.out.println("Connection Establish");
PreparedStatement ps=con.prepareStatement("Select * from product where p_name=? ");
ps.setString(1, Name);
ResultSet rs=ps.executeQuery();
while(rs.next())
{
id=rs.getInt("id");
p_price=rs.getInt("p_price");
}
}
}

Output

Try code to see proper output

Happy Coding :)