Populating combobox in CodeNameOne - java

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.

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.

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 can I populate my JTable with my embedded database?

I am having trouble showing my database filled JTable within my GUI application.
My code below runs through and creates a GUI with a panel, I then create my JTable and add it onto my application. I then run through a method that supposedly populates the table. After the populating has finished, nothing shows.
Dissecting my code, I'm led to believe somewhere is causing the data not to parse into my table, for some unknown reason, which is why I have come here.
At the click of a button, this code entails:
JTable tigerTable = new JTable();
JPanel centerPanel = new JPanel();
centerPanel.add(tigerTable, new GridBagConstraints());
FillTable(tigerTable, "SELECT * FROM TIGER_INFO");
The FillTable method as follows:
//Add buildTableModel method
public void FillTable(JTable table, String Query)
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:derby:STOCK_CONTROL");
Statement stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stat.executeQuery(Query);
System.out.println("Connected");
//Remove previously added rows
while (table.getRowCount() > 0)
{
((DefaultTableModel) table.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next())
{
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++)
{
row[i - 1] = rs.getObject(i);
}
((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stat.close();
conn.close();
}
catch (InstantiationException |
IllegalAccessException |
ClassNotFoundException |
SQLException e)
{
System.out.println(e);
e.printStackTrace();
}
}
Doing so creates the application, but does not show any table with data. My database contains 3 columns and 3 rows, but I do not see my data displayed inside a JTable.
My question is, how can I populate my JTable with my database and display it correctly on my GUI application?
If you need anything else, please let me know and I will provide as much as I can.
Thank you in advance.
I think you mix the operation, i suggest to use this instruction :
Create a Bean, or Entity to store the information of your Object
Get the List of your data,
Display your data in your JTable,
So you can use this to display your data in your JTable :
....
List<TIGER_INFO> list = new ArrayList<>();//create a List of data
while (rs.next()){
//fill data in your List
list.add(new TIGER_INFO(rs.getTYPExxx("att1"), rs.getTYPExxx("att2"), rs.getTYPExxx("att3"));
}
//when you finish call your function which display your data :
fillData(list);
....
Fill date method can look like this :
private void fillData(List<TIGER_INFO> list) {
DefaultTableModel model = (DefaultTableModel) jTableName.getModel();
while (model.getRowCount() > 0) {
for (int i = 0; i < model.getRowCount(); i++) {
model.removeRow(i);
}
}
for (TIGER_INFO obj : list) {
model.addRow(new Object[]{
obj.getAttribute1(),
obj.getAttribute2,
obj.getAttribute3
});
}
}
I recommend to write a class extending AbstractTableModel. Add a function to this class filling the content based on a SQL-Statement. Then it will look something like:
TigerTableModel tigerModel = new TigerTableModel(dbConnection);
tigerModel.executeQuery("select * FROM TIGER_INFO");
JTable tigerTable = new JTable(tigerModel);
or you create a generic TableModel that is able to run every SQL-statement, so you are very flexible in your project.
I have found the solution - I've been trying to wrap my head around the problem for way too long, and I finally fixed it.
Try setting the table model manually first.
JTable tigerTable = new JTable();
tigerTable.setModel(new DefaultTableModel(0, numberOfColumns));
When you don't specify a model, the JTable creates an anonymous inner class and generally doesn't behave how you want it to.

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.

Setting a default value in a jcombobox populated by a query

I am currently writing a program in Java that uses a query populated jcombobox. I was wondering if there is a way to have a default selected value when the program executes. My query is a list of languages listed alphabetically, but I am curious if it is posible to have English (which is in the middle of the list) be the default value.
I know that when you manually hard code the values into the jcombobox you can set the default variable as
jcombobox.setSelectedIndex(int anIndex);
or
jcombobox.setSelectedItem(Object anObject);
but I am unsure when a ResultSet loops and populates the jcombobox.
Currently my code is:
languageLabel =new JLabel("Languages:");
rowFour.add(languageLabel,BorderLayout.WEST);//adding to my current panel
langbox = new JComboBox();
rowFour.add(langbox,BorderLayout.WEST);
try
{
con = DriverManager.getConnection ("jdbc:oracle:thin:#localHost:portNumber:ORCL", "username", "password");
statement = con.createStatement();
}
catch(SQLException sqle)
{
System.out.println(sqle);
}
langbox.removeAllItems();
langbox.addItem("Please Select...");
try
{
ResultSet rs = statement.executeQuery("select language from language order by 1");
while (rs.next())
{
langbox.addItem(rs.getString(1));
//Thinking that this is where a default value would be located
}
}
catch(Exception e)
{
System.err.println(e);
}
Thank you for your time.
ResultSet rs = statement.executeQuery("select language from language order by 1");
while (rs.next()) {
langbox.addItem(rs.getString(1));
//I'm thinking that this is where a default value would be located
if(rs.getString(1).equals(myDefaultLanguageVariable)) {
langbox.setSelectedItem(rs.getString(1));
}
}
btw: You should clean up that code, its not good that way.

Categories

Resources