How can I insert data into JComboBox using JTextField - java

I have write program that program have 2 frame one frame to add item and save to database
in another frame I have to select the item which is add in first frame in JComboBox I write that code for insert data into database but I don't know how to display in JComboBox
try {
String host = "jdbc:derby://localhost:1527/PROCAT";
String uName = "zain";
String uPass = "zain";
con = DriverManager.getConnection(host, uName, uPass);
String m = "insert into ITEMB (ITEM,ITEMNAME,PRISE) values(?,?,?)";
ps = con.prepareStatement(m);
ps.setInt(1, Integer.parseInt(jTextField3.getText()));
ps.setString(2, jTextField2.getText());
ps.setString(3, jTextField4.getText());
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "record saved");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
This for JComboBox:
try
{
String host = "jdbc:derby://localhost:1527/PROCAT";
String uName = "zain";
String uPass = "zain";
con = DriverManager.getConnection(host,uName,uPass);
st = con.createStatement();
rs = st.executeQuery("select ITEMNAME from ITEMB;");
while (rs.next()) {
jCom.addItem(rs.getString("ITEMNAME"));
}
}
catch(Exception ex) {
JOptionPane.showMessageDialog(null,ex);
}

On my understanding, there are 2 frames. One of them is for viewing records and has the JComboBox, the other one is for inserting records and has the JTextField.
The default frame would be the one with the JComboBox. If you want to add a new record into the JComboBox, a frame will appear for adding of records.
Once the INSERT statements are issued, the frame with the JTextField will be closed and the frame with the JComboBox will appear showing the newly added records.
You can provide a Reload button for deleting the items inside the JComboBox and then reloading the data using the SELECT statement.
while (rs.next()) {
jComboBox.addItem(rs.getString("ITEMNAME"));
}
And then, use
jComboBox.repaint();

Related

JComboBox error blocking another field display

I have a problem with JComboBox. It's blocking another field in a frame meant to display another value that is linked through a foreign key in a database, a value that depends on the combo box already pop out. But somehow, after the user clicks the combo box it is blocking another field. The app is using MySql.
Here's the code:
ComboBox method to fill value from DB
public void comboBoxBerat(){
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
try {
sql = "SELECT * FROM weight_of_services";
rs = stat.executeQuery(sql);
while (rs.next()) {
jComboBoxBerat.addItem(rs.getString("weight"));
}
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
Action when selection is made from combo box, its get the value that linked with foreign key
private void jComboBoxBeratActionPerformed(java.awt.event.ActionEvent evt) {
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
String item = (String)jComboBoxBerat.getSelectedItem();
String sql = "SELECT price FROM weight_of_services WHERE weight = ?";
try {
pst = con.prepareStatement(sql);
pst.setString(1, item);
rs = pst.executeQuery();
if (rs.next()) {
String price = rs.getString("price");
txtHargaBerat.setText(price); //put value from combobox to txtField
}
con.close();
} catch (Exception e) {
}
}
The problem after I select from the box its blocking another field.
This is the combo box problem in the frame
It's solved. This because i am using jpanel for customizing color for the frame. Its just so messed up with the stacking one panel on top of the other one. That's why my dropdown list get blocked. So what I did, removed all the panel. Custom and sorting it more carefully and tidy from the start.

How to make the table size same as the row size in java?

I have retrieved data from SQL Database into a JTable. I want to make the table size to be automatically the size of the rows. It would be plus if I can also make the data in the rows centered.
I am fairly new to GUI Java Programming. Can someone please let me understand how it can be done?
private void DisplayOrder() {
String qry = "SELECT * FROM SALESORDER"; //Creating Query
try {
conn = DriverManager.getConnection(connectionUrl, username, Pass);
Statement st = conn.prepareStatement(qry);
ResultSet rs = st.executeQuery(qry);
while (rs.next()){
String Des = rs.getString("ProductDescription");
String qty = String.valueOf(rs.getInt("Quantity"));
String price = String.valueOf(rs.getInt("TotalPrice"));
String tbdata[] = {Des, qty, price};
DefaultTableModel model = (DefaultTableModel) Ordertable.getModel();
model.addRow(new Object[]{Des, qty, price});
}
} catch (SQLException e){
} finally{
Ordertable.getTableHeader().setFont(new Font("Segoe UI",Font.BOLD,15));
Ordertable.getTableHeader().setOpaque(false);
Ordertable.getTableHeader().setBackground(new Color(32,136,203));
Ordertable.getTableHeader().setForeground(new Color(255,255,255));
Ordertable.setRowHeight(25);
}
}

how do i update my jtable after i add or delete my item

Im currently developing a database project. my jtextfield, addbutton, editbutton and the jtable was originally on one jframe. but when i made a addbutton to open another jframe and place the items to be added there, it works but it does not update my jtable, my jtable only updates after i make another action like editing or adding another item, what should be the problem here? here are the example of my edit button. btw i need it to be inserted and updated into my mysql
if(editID.getText() != null)
{
String UpdateQuery = null;
PreparedStatement ps = null;
Connection con = main.getConnection();
try{
UpdateQuery = "UPDATE mydatabase SET name = ?, price = ?"
+ ", quantity = ? WHERE id = ?";
ps = con.prepareStatement(UpdateQuery);
ps.setString(1, editName.getText());
ps.setString(2, editPrice.getText());
ps.setString(3, editQuantity.getText());
ps.setString(4, editID.getText());
ps.executeUpdate();
main.getProductList();
main.Show_Products_In_JTable();
JOptionPane.showMessageDialog(null, "Product Updated");
}catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}else{
JOptionPane.showMessageDialog(null, "One Or More Fields Are Empty Or Wrong");
}
so here is the two methods that i used to edit the table... but it seems incomplete, like i need a method in the main to simultaneously refresh my jtable. my brain are really exploding right now with this problem. cause i cant see any problem why moving my edit method from another jframe could affect my program.
public ArrayList<Database1> getProductList()
{
ArrayList<Database1> productList = new ArrayList<Database1>();
Connection con = getConnection();
String query = "SELECT * FROM mydatabase";
Statement st;
ResultSet rs;
try {
st = con.createStatement();
rs = st.executeQuery(query);
Database1 mydatabase;
while(rs.next())
{
mydatabase = new Database1(rs.getString("id"),rs.getString("name"),rs.getInt("price"),rs.getInt("quantity"));
productList.add(mydatabase);
}
} catch (SQLException ex) {
Logger.getLogger(mainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
return productList;
}
public void Show_Products_In_JTable()
{
ArrayList<Database1> list = getProductList();
DefaultTableModel model = (DefaultTableModel)itemTable.getModel();
model.setRowCount(0);
Object[] row = new Object[4];
for(int i = 0; i < list.size(); i++)
{
row[0] = list.get(i).getId();
row[1] = list.get(i).getName();
row[2] = list.get(i).getQuantity();
row[3] = list.get(i).getPrice();
model.addRow(row);
}
itemTable.setModel(model);
model.fireTableDataChanged();
}

Need help regarding jComboBox and jTable

So i have this jTable on my frame and a jComboBox. Inside my jComboBox is the list of phones. What i want to do is to have the jTable get the database of a specific product inside the jComboBox. Suppose i pick the Samsung S7 in the jComboBox. When i click the "Details" jButton the jTable will show the Data of Samsung S7(Model, Price, Stock, etc.). How do i do this? Here is my code:
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/projectephone","root","");
String sql= "select * from samsung";
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs= pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Failed to add");
}
}
But this code just make my jTable show all of my data inside my database table. Any ideas?
When the details button is clicked
get the current selected phone from the JComboBox (given as phone name or internal id into your database table or whatever)
and then use this value to limit your search.
For example
String phoneName = ... // current selected in the the combobox
String sql= "select * from samsung where name = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, phoneName);
ResultSet rs= pst.executeQuery();

How I write this function so that each time i returns me new record of table on the screen

private void next_contactActionPerformed(java.awt.event.ActionEvent evt) {
String name, lName, add, em, cell = null;
try {
String Url = "Jdbc:Odbc:DirDSN";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(Url,"sa","mysql");
//Statement st = con.createStatement();
String sql = "SELECT * FROM PersonInformation";
PreparedStatement pstmt = con.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
name = rs.getString("First_Name");
lName = rs.getString("Last_Name");
add = rs.getString ("Address");
em = rs.getString("Email_Id");
cell = rs.getString("cell#");
jTextField2.setText(name);
jTextField3.setText(lName);
jTextField4.setText(add);
jTextField5.setText(em);
jTextField10.setText(cell);
}
con.close();
} catch(Exception sqlEx) {
System.out.println(sqlEx);
} finally {
}
}
I have written this next function for next button. I want when I click the next button the rs.Next() returns a new record of table on the screen. Now I am facing the problem that each time when I click the next button I get the first row of the table. I have also used while (rs.Next()) but it returns me the last row of table each time I click the next button. Please tell me how I can write this function such that each time I call this function it returns a new record from the table.
Change ResultSet rs to a member variable or save the position you're in and use it as a parameter for the method (see LIMIT).
At the moment, you create a new ResultSet with every click, always starting at index 0.

Categories

Resources