How to get database values in combo_box? - java

I am working on a small project which assigned to me by my teacher I am beginner to java
I have used combo box in my form to fetch data from database... I am able to get the data
from the database while clicking on item1 in the combo box.. I want to get rid of item
so that i can get values directly here's my code...
import java.sql.*;
Statement stmt=null;
Connection con=null;
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=DriverManager.getConnection("jdbc:odbc:sql_login");
stmt=con.createStatement();
String search="select * from tblflight";
ResultSet rs=stmt.executeQuery(search);
while(rs.next())
{
Date d1 = new Date(rs.getDate("departure_date").getTime());
combo_box.addItem(d1);//
}
rs.close();
con.close();
}catch(Exception e)
{
e.printStackTrace();
}
combox[ITEM1,ITEM2,ITEM3,ITEM4]//When form displays it shows these items
but when I remove these items from properties I found combobox empty
!![this is the first img when i open my form][1]
![this is the second img when i click any of the item][2]
![1]: http://i.stack.imgur.com/ez5fa.png "hidden"
![2]: http://i.stack.imgur.com/orlDK.png "hidden"

To get selected value you can do it as follows,
String sSelectedValue = combobox.getSelectedItem().toString();
To get selected item index
int iSelectedItemIndex = combobox.getSelectedItemIndex();
To remove item.
combobox.removeItemAt(index); //index is the index of the item you want to remove from the list.

Related

How to search in a string saved in MySQL database

I have created a JList by taking inputs from user in jtextField. Then I have saved the jList to Mysql database by converting the JList to String as I want to save the JList item in a single row as single entry.
code for adding user input to jList:
DefaultListModel dlm= new DefaultListModel();
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String userInput= jTextField2.getText();
dlm.addElement(userInput);
jList1.setModel(dlm);
jTextField2.setText(null);
}
Code Used for saving the JList into MySQL database as String:
String allitem=null;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
for(int i = 0;i<jList1.getModel().getSize();i++)
{
allitem = (String)jList1.getModel().getElementAt(i)+"::"+allitem;
}
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ft", "root", "");
PreparedStatement stmt = conn.prepareStatement("insert into ftt (listname,listitem) values (?,?)");
stmt.setString(1, jTextField1.getText());
stmt.setString(2, allitem);
stmt.execute();
conn.close();
}catch(
Exception e)
{
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
JOptionPane.showMessageDialog(null, "done");
}
Now in the next page user can view all the Strings (Jlist is saved as String) item in the JList. I wan to disaplay user the details of the JList item selected. I have created a Jtable and want to display the other details of the JList item selected.
Code I have Tried:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
Update_table1();
}
private void Update_table1(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/ft","root","");
String query="SELECT listname FROM ftt WHERE listitem=?;";
PreparedStatement prepstmt=conn.prepareStatement(query);
String s = (String) jList1.getSelectedValue();
prepstmt.setString(1,s);
ResultSet rs=prepstmt.executeQuery();
jTable3.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
But when using this code the Jtable is not showing any value although it is taking the table header name. Please can anyone check I correct in how to search in the String saved in MySQL database. I think the problem is there as other things are working fine.
note: Its not showing any error or exception.
It is not the best way to keep record as the way you are doing as concatenated string. You better use a normalized table and keep all list elements as a record. For your code you are trying to query on a field which contain concatenated information. So you may use "like" keyword instead of "=".
"SELECT listname FROM ftt WHERE listitem like %?%;"

JComboBox only show one item from database

I'm trying to display database item into a JComboBox and this is my code.
public static void checkItemName(){
Connection conn = SQLite.SQLite();
String sql = "select itemname from item";
try{
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
String list = resultSet.getString("itemname");
purcItemName.addItem(list);
conn.close();
}
} catch (SQLException lol){
System.out.println(lol.toString());
}
}
I did declare static JComboBox purcItemName; and purcItemName = new JComboBox();
The method/function will be called then user press login button.
The problem I'm having now is that, it only shows one item while my database has multiple items.
Anyone got an idea why?
Vector v = new Vector();
while (resultSet.next()){
String list = resultSet.getString("itemname");
v.add(list);
}
conn.close();
purcItemName.setModel(new DefaultComboBoxModel(v));
store the data you got from database in a vector object and once that is completed set the vector object in your combobox as a new model. try this one
and don't close the connection inside your loop.
you are closing connection inside resultSet.next() check, put the conn.close() outside, to the end

Get record using JComboBox from database and get another record to textfield following combobox record?

Can I know how we can get record using JComboBox from database and at the same time get another record from database to JTextField following what we choose in combobox?Both records are in database.
Example:Get employees name from database using combo box, make selection using the combo box, then get employee id in text field...
Thank you.
I'm trying to make a Java frame program having a text area, a combo box link to database which is stock items name and a text field for fill in stock items id. User either use combo box choose items name show items id in text field or fill in items id to show the item name in the combo box automatically.
How do I do that actually?
try {
// Load the driver
Class.forName(
"sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn = DriverManager.getConnection(db);
System.out.println("Database connected.");
s = cn.createStatement();
ResultSet rs1=s.executeQuery("select StockName from StockDetail");
while (rs1.next()){
itemCombo.addItem(rs1.getString("StockName"));
}
/*String sl;
sl = "select StockID from StockDetail where StockName='" + stockno.getText();
ResultSet rs2 = s.executeQuery(sl);
while(rs2.next()){
stockno.setText(rs2.getString("StockID"));
}*/
rs1.close();
s.close();
cn.close();
} catch(Exception e) {
System.out.println(e.toString());
}

Problems in FocusListener-Swing

In my application i have used a Frame which consists of auto-complete details,i.e.,if we select Name,automatically details of that Name will be displayed.
For selecting name i have used a Separate textfield with Drop-down, similar to Auto-complete.
But when i go to the name section and click names using Mouse,its getting selected,the same when i did using Keyboard Navigation keys,Focus doesn't stays in Textfield,even after selecting the textfield with mouse and use Keyboard ,its not getting focus.
Hope m clear,I'm Sorry if you couldn't get what i mean ..
I suggest you use JComboBox rather than JTextField for Drop-Down
Use loadCombo() method to add names in JComboBox.
Then use
jComboBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
Object name=jComboBox.getSelectedItem();
//Make DB connection on name and fetch the details
//Use double vector for fetching data
Vector<Vector<String>> data = new Vector<Vector<String>>();
data=getDetails();
Stsem.out.println(data);//To print data (for Confirmation that it works fine)
JOptionPane.showMessageDialog(this,data);
private Vector<Vector<String>> getDetails(Object name) {
//DB Connections
PreparedStatement pre = conn.prepareStatement("select * from Table");
ResultSet rs = pre.executeQuery();
while(rs.next())
{
Vector<String> item = new Vector<String>();
item.add(rs.getString(1));
item.add(rs.getString(2));
...
itemVector.add(item);
}
/*Close the connection after use (MUST)*/
if(conn!=null)
conn.close();
return itemVector;
}
});

JComboBox selects the first item by iteself

I have made a combobox which is being filled up with the database entries. The problem that i'm currently facing is that when I write "H" the list gets filled with all the names starting with "H" as required but the first name in the list automatically gets selected. How to avoid this problem?
String ch = text.getText();
if (ch.equals("")) {
combo.setVisible(false);
} else {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/userlogin", "root","12345");
Statement st = connect.createStatement();
ResultSet rs = st.executeQuery("SELECT author_name FROM scrpd_authors WHERE author_name LIKE '"+ ch + "%'");
while (rs.next()) {
String name = rs.getString("author_name");
if (name.equals("")) {
searchitems.addItem("");
} else {
searchitems.addItem(rs.getString("author_name"));
searchitems.setVisible(true);
}
}
connect.close();
} catch (Exception ex) {
}
}
Please note the combobox is being filled with all my desired entries based on the mysql query, the problem is just with the selection of the first entry by itself.
the first name in the list automatically gets selected. How to avoid this problem?
Then use:
comboBox.setSelectedIndex(-1);
after the data has been loaded.
Or maybe you could use a Combo Box Prompt.
that's a quirk of the not-editable JComboBox when adding to an empty box:
using addItem(item) will select that item
using insertItemAt(item, 0) will not select that item
That quirk is independent on whether the filling happens on the model or on the view-
So if deselecting after filling the model (as suggested by Rob) is not an option, you can use the insert method (either on the view or on the model):
// model
model.addElementAt(item, model.getSizes();
// alternatively view
combo.insertItemAt(item, combo.getItemCount());
Generally, it's recommended to do model manipulations on the model (vs. on the cover methods on the view) - this way you can implement and test your model handling independent of the view.

Categories

Resources