JComboBox selects the first item by iteself - java

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.

Related

update the picture in database

Hello! I am creating an app for students database. Recently I got a problem when I want to change data that is related to the specific student. Especially problems occur when I want to change the picture for the specific student. I need to check if the picture belongs to the student or not. I store my pictures to the folder if I change the picture, I delete previous one and create a new one. My question about how to check if a picture belongs to the specific student?
I check students in this way.
// get the name of the student from first table getValueTableName
// get the name of the picture from first table getValueTablePicture
getValueTableName = jTable1.getModel()
.getValueAt(jTable1.getSelectedRow(), 0).toString();
getValueTablePicture = jTable1.getModel()
.getValueAt(jTable1.getSelectedRow(), 3).toString();
File sourceFile = new File(getValueTablePicture);
setPicture = sourceFile.getName();
// GET NAME OF THE STUDENT AND THE PICTURE FROM DATABASE AND COMPARE
// THEM TO THE CURRENT USER
try {
CallableStatement statement = null;
Connection data = getmyConnection();
statement = data.prepareCall("{call editStudentByName}");
myResults = statement.executeQuery();
while (myResults.next()) {
// COPY PATH IN getEditName
getEditName = myResults.getString("Name");
// COPY PATH IN getEditPicture
getEditPicture = myResults.getString("Picture");
// add students from database to array
// mylist.add(getEditName.concat(getEditPicture));
mylist.add("\n");
}
myResults.close();
} catch (Exception c) {
c.printStackTrace();
}
// I don't know how to move from this point when I check names with loop
// I check the student with the loop
for (String person : mylist) {
if (getValueTableName.concat(sourceFile.getName()).equals(person) == true) {
}
System.out.print(getValueTableName.concat(sourceFile.getName())
.equals(person));
errors.append(
"- Please choose another picture or rename it!\n Picture ")
.append(getEditPicture)
.append(" is exist for a student " + getEditName)
.append("\n");
jTextField3.requestFocusInWindow();
jTextField3.setText("");
}
The very first thing I'd do is not using separate Strings with strange names like getEditName - this is confusing. Consider having POJO (Student.class) and working with that
So you want to replace single student picture? Why do you have to iterate some array in this case? You should get single student from database (by Id or via some unique set of attributes).
Ok, lets say you have a list of students and you iterate over it. But you still have to change picture for single person so that there is no need to check.
Simply do
String pictureFileName = person.getPicture();//assming getPicture() method returns current picture path
and then save new picture with the same name. In this case old picture will be overwritten so that no issue with checks.
UPD:
If you want to check for picture existence you can do the same:
String pictureFileName = person.getPicture();
File f = new File(pictureFileName );
if(f.exists() && !f.isDirectory()) {
// do something, say report warning
}
UPD:
If you don't require an ability for students to share same file as a picture it's better to implement this at DB level as well via this https://www.w3schools.com/sql/sql_unique.asp - so that you simply won't be able to write two different student records with the same picture path field. In this case checks won't matter anymore and you can simply overwrite the picture file because it belongs to single student only
Finally, I got my things done. It was a very painful moment, but I got what I wanted. The problem was hidden in a column "Picture" in the table "Student" of my database. First, I add UNIQUE constraint ensures to my column that all values in a column are different. Second, I created two stored procedures:
CREATE DEFINER=`root`#`localhost` PROCEDURE `checkStudentByPicture`(
in picture_name varchar(100)
)
BEGIN
SELECT COUNT(*) FROM students_center.Student st WHERE st.Picture = picture_name;
END
The first procedure checks if my column has unique names and doesn't allow to add the same name to the column.
And I created a second one:
CREATE DEFINER=`root`#`localhost` PROCEDURE `getStudentNameByPicture`(
in name varchar(45),
in pic_name varchar(100)
)
BEGIN
SELECT COUNT(*) FROM students_center.Student st WHERE st.Name = name and st.Picture=pic_name;
END
The second procedure checks if the column "Picture" is related to the column "Name". If the column "Picture" is not related, the user doesn't allow to change the name.
Here is the code about checking if my data related to context:
private boolean validateFieldEditStudent() {
StringBuilder errors = new StringBuilder();
// call stored procedure checkStudentByPicture
File sourceFile = new File(jTextField3.getText());
String checkStudentName=jTable2.getValueAt(jTable2.getSelectedRow(), 0).toString();
try {
CallableStatement statement = null;
Connection data = getmyConnection();
statement = data.prepareCall("{call checkStudentByPicture(?)}");
statement.setString(1, sourceFile.getName());
myResults = statement.executeQuery();
while (myResults.next()) {
//COPY PATH IN pictureName
getPictureCount = myResults.getInt(1);
}
myResults.close();
} catch (Exception c) {
c.printStackTrace();
}
}
// call stored procedure checkStudentByPicture
try {
CallableStatement statement = null;
Connection data = getmyConnection();
statement = data.prepareCall("{call getStudentNameByPicture(?, ?)}");
statement.setString(1, checkStudentName);
statement.setString(2, sourceFile.getName());
myResults = statement.executeQuery();
while (myResults.next()) {
//COPY PATH IN pictureName
getStudentNameCount = myResults.getInt(1);
}
myResults.close();
} catch (Exception c) {
c.printStackTrace();
}
//check if data is related to the specific user
if(getFileChooserCount > 0) {
if(getStudentNameCount != 1) {
if(getPictureCount == 1) {
errors.append("- Picture "+sourceFile.getName()+" existed in the database!\n");
jTextField3.setText("");
jTextField3.requestFocusInWindow();
}
}
}
if (errors.length() > 0) {
JOptionPane.showMessageDialog(EditStudent, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}

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 get database values in combo_box?

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.

Populating combobox in CodeNameOne

I'm having a slight problem when populating a combobox from the column of a database. below is my code:
protected void initComboBoxModel(final ComboBox cmp) {
try {
String sql = "SELECT * FROM stockinfo";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
Vector vec = new Vector();
while (rs.next()) {
String item = rs.getString("Parts");
Hashtable h = new Hashtable();
h.put("cmp", item);
vec.addElement(h);
cmp.setModel(new DefaultListModel(vec));
}
} catch (Exception ex) {
Dialog.show("Error", "initComboBoxModel count not populate the combo box.", "OK", null);
}
}
The combobox populates but there is unnecessary text in each option in the combobox, for example:
an option which should say "Hello" says "{cmp = Hello}".
How do i stop this from happening? it occurs for every item in the combobox.
Thanks in advance:)
Marko
The problem you are facing is that you are creating a Vector<HashTable> so when you are populating the combobox the default renderer takes toString() method from each hashtable.
I don't know why you need a hashtable, but that's the problem why you are stuck.
Im not familiar with codeNameOne but in swing JComboBox by default uses a renderer wich uses toString() method to display object data. So you can make your own renderer class to customize the view.
UPDATE
I modify your code and comment code, assuming you are using java 1.5 or above.
protected void initComboBoxModel(final ComboBox cmp) {
try {
String sql = "SELECT * FROM stockinfo";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
Vector<String> vec = new Vector<String>(); // use generics
while (rs.next()) {
String item = rs.getString("Parts");
vec.addElement(item);
}
cmp.setModel(new DefaultListModel(vec)); // here you set the model
} catch (Exception ex) {
Dialog.show("Error", "initComboBoxModel count not populate the combo box.", "OK", null);
}
}
Now it's gonna to work you don't have to use any renderer cause you add Strings so toString method is fine in this case.
It won't work for you on the device, you changed the classpath to add JDBC which you shouldn't have.
You should use a renderer or a MultiList to have the hashtable entries render correctly.

Fitting a whole row of a MySQL table onto a single JLabel in Java

I have Java code the successfully connects Java to MySQL.
I have two classes. One that creates the GUI with Java and another class that specifically gets information from MySQL.
I'm trying to find a good way to put a whole row of information as a String into each JLabel on MyGUI.
Here is my code in each class (excluding connecting to the database):
CLASS 1
String result = "";
contactsList()
{
//extra classes
db=new database();
result = db.getContact();
label1 =new JLabel(result);
CLASS 2
PreparedStatement pst, pst2;
ResultSet rs, rs2;
pst2 = con.prepareStatement("select LastName, FirstName from contacts");
public String getContact()
{
String result2 = "";
try {
rs2=pst2.executeQuery();
while (rs2.next())
{
result2 = rs2.getString(1);
}
return result2;
}
catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("error while validating"+e);
return "";
}
}
Right now the rows in my Contacts table in MySQL has columns separated by commas
1, Rivera, Angelo, 2890 something st. ventura 93003, Null
2, Person, Random, 1223 I dunno ave. Camairllo 93001, 423-123-5313
Right now when I try to put a whole row in the "label1" the only text it shows is "Person".
How do I make it so it shows the whole Row in the JLabel?
Also how would I format the code so I can call the the function to get the next row of information and put it into another label?
Thanks.
You are only asking it to retrieve one column from your result set by the looks of things :
result2 = rs2.getString(1);
If you want to display more data, you just need to retrieve it and format it somehow :
result2 = rs2.getString(1) + " : " + rs2.getString(2);
for example.
But there are other problems with the select statement I think.
select LastName, FirstName from contacts
will retrieve the LastName and FirstName from every row in the database. The way your loop construct works means that result2 will contain the data for the last row in the table only. Is that what you are trying to achieve?
I would suggest using a JTable for this. Read the section from the Swing tutorial on How to use JTable for more information.
Then you might want to check out Table From Database. The Table From Database Example code may be the easiest way to start.

Categories

Resources