Problems in FocusListener-Swing - java

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

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 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 %?%;"

Problem populating a Jlist based on two Jcomboboxes connected to a PostgreSQL database

Good afternoon
I'm working on a project in witch I have to calculate the performance of a pump for certain parameters like rotation, number of stages, diameter and viscosity. At first I created a database using PostgreSQL with several commercial pumps. The database contains schemas as the companies that manufacture the pumps, in each schema there are tables representing the different series of pumps and the tables have several pumps organized as lines. The lines contains coefficients that represent the pumps and that are necessary to calculate the performance.
I tried to code the application in C++, but was too hard to connect with Postgre, so I ended working with Java and Netbeans (I think it's easier to newcomers). The application is running quite good so far, but I have found two problems that I cannot solve.
To select the pump to make the calculations I had to use two Jcomboboxes and a Jlist. The first Jcombobox is for selecting the manufacturer, the second to select the serie. Finally, the Jlist displays all the pumps in that serie so the user can select one.
I was able to populate the first Jcombobox with the schemas of the database (thanks to you guys, actually), the second with the tables of the schema selected in the first and the Jlist with the names of the pumps.
The first problem is that I cannot clear the second Jcombobox (the series one) after changing the selected manufacturer in the first Jcombobox, it will add more itens every time that I change the first Jcombobox, even if I re-select an item that was already selected. I tried using the command "removeAllItems()", but then it displays just one table and stop filling the Jcombobox.
The second problem is that, when I select a serie in the second Jcombobox, it doesn't immediately display the pumps in the Jlist, the Jlist starts displaing after I select another serie. So, I have to select one and then change to another so the pumps start appearing in the Jlist.
I'm sorry for the long text and the english errors, I hope its enough for you guys to understand. I know the code is not pretty, that's because I'm not so good at this yet and I'm in a bit of a hurry to deliver it.
Here is the code, without all the generated code that Netbeans does.
public final class LabPump extends javax.swing.JFrame {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
public LabPump() {
initComponents();
con = ConnectPump.connect();
FillSelectFabricante();
}
public void FillSelectFabricante(){
try {
rs = con.getMetaData().getSchemas();
while(rs.next()){
String schemas = rs.getString("TABLE_SCHEM");
if(schemas.equals("information_schema") || schemas.equals("pg_catalog")){
}
else{
selectFabricante.addItem(schemas);
}
}
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
public void FillSelectSerie(String fabricante){
//selectSerie.removeAllItems();
try {
String[] sql = {"TABLE"};
rs = con.getMetaData().getTables(null, fabricante, "%", sql);
while(rs.next()){
String tables = rs.getString(3);
selectSerie.addItem(tables);
}
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
public void FillListBomba(String fabricante, String serie){
DefaultListModel dlm = new DefaultListModel();
dlm.removeAllElements();
try{
String sql = "select * from " + fabricante + "." + serie;
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
String bomba = rs.getString("bomba");
dlm.addElement(bomba);
}
listBomba.setModel(dlm);
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
private void selectSerieActionPerformed(java.awt.event.ActionEvent evt) {
selectSerie.addActionListener((ActionEvent e) -> {
String fabricante = selectFabricante.getSelectedItem().toString();
String serie = selectSerie.getSelectedItem().toString();
FillListBomba(fabricante, serie);
});
}
private void selectFabricanteActionPerformed(java.awt.event.ActionEvent evt) {
String fabricante = selectFabricante.getSelectedItem().toString();
FillSelectSerie(fabricante);
}
Thank you all.
I managed to solve the problem just now. When the selectSerie.removeAllItems() line was uncommented the program returned a NullPointerException error.
To solve the problem I used the DefaultComboBoxModel class and then used the RemoveAllElements() method. I'm not quite sure why the other method didn't work though.
Thanks for your time and help Peter.
public void FillSelectSerie(String fabricante) {
DefaultComboBoxModel box;
box = new DefaultComboBoxModel();
box.removeAllElements();
try {
String[] sql = {"TABLE"};
rs = con.getMetaData().getTables(null, fabricante, "%", sql);
box.addElement("-");
while (rs.next()) {
String tables = rs.getString(3);
box.addElement(tables);
}
selectSerie.setModel(box);
} catch (SQLException error) {
//JOptionPane.showMessageDialog (null,error);
}
}

how to update the jcombobox immediately when the table in database get updated in java

I am working on java application.I have two frames in application.I want to reflect data entered in one frame into another frame run time.
As shown in above window when I press submit button in supplier window combobox in puchase window should get updated immediately.
What necessary changes should I make?
here is my code of frame1 to store data in database :
public void btnSubmitAction(ActionEvent e){
String custId,custNm;
if(txtSupplierID.getText().equals("") || txtSupplierName.getText().equals("") )
{
System.out.println("Please enter valid information!!!!!!!");
}
else
{
try{
setConnectin();
String str = "Insert into SupplierMasterTable values(?,?)";
pstmt = conn.prepareStatement(str);
pstmt.setString(1,txtSupplierID.getText());
pstmt.setString(2, txtSupplierName.getText());
int x = pstmt.executeUpdate();
System.out.println("Supplier registered successfully");
txtSupplierID.setText("");
txtSupplierName.setText("");
conn.close();
}catch(Exception e1){
e1.printStackTrace();
}
}
}
And here is my code of frame2 to get data from database :
JComboBox comboBoxVenderName = new JComboBox();
comboBoxVenderName.setFont(new Font("Times New Roman", Font.PLAIN, 15));
comboBoxVenderName.setBounds(144, 88, 137, 21);
panel.add(comboBoxVenderName);
try{
setConnectin();
String str = "select * from SupplierMasterTable";
stmt = conn.createStatement();
rs = stmt.executeQuery(str);
while(rs.next())
{
comboBoxVenderName.addItem(rs.getString("Supplier_Name"));
}
conn.close();
}catch(Exception e2){
e2.printStackTrace();
}
I have gone through following links but does not get the feasible solution :
Immediate update to JCombobox in Java
Synchronize a jCombobox with a MySQL Table
JComboBox comboBoxVenderName = new JComboBox();
Don't create a new combo box when you want to refresh the data.
Instead you should create a new DefaultComboBoxModel and add the data to the model. Then you update the data in the existing combo box by using:
comboBox.setModel( the updated model );
Also, don't use a null layout!!! You should not be using the setBounds() method. Swing was designed to be used with layout managers.

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

Categories

Resources