Adding items to combo box in a table in netbeans

Sajith

I have a table and one of its columns needs to contain combo boxes.

When I run the following code, I get combo boxes in each cell but the items are not added into it. When I try to print the items using system.out.println(val), they get printed but they do not get added to the combo box.

How can I do it?

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {  

    for(Entry<String, HashSet<String>> avar : Annotation.resultSet.entrySet()) {
        Object[] row = new Object[2];
        row[0] = avar.getKey();
        JComboBox comboBox = new JComboBox();
        int i = 1;

        DefaultTableModel model = (DefaultTableModel) annoTab.getModel();
        model.addRow(row);
        TableColumn valueColumn = annoTab.getColumnModel().getColumn(1);
        setUpValueColumn(valueColumn, avar.getValue());
    }  
}                                        

public void setUpValueColumn(TableColumn sportColumn, HashSet<String> values) {

    JComboBox comboBox = new JComboBox(new DefaultComboBoxModel(values.toArray()));

    for(String val : values) {
       System.out.println(val);
       comboBox.addItem(val);
    }

    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));

   ComboBoxTableCellRenderer renderer
                = new ComboBoxTableCellRenderer();
   sportColumn.setCellRenderer(renderer);
}

Full Code

AnnotationGeneration.java

public class AnnotationGeneration extends javax.swing.JFrame {

    class ComboBoxTableCellRenderer extends JComboBox implements TableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            setSelectedItem(value);
            return this;
        }
    }

    public AnnotationGeneration() {
        initComponents();       
        DefaultTableModel model = (DefaultTableModel) annoTab.getModel();
        while(model.getRowCount() > 0){
            for(int i = 0 ; i < model.getRowCount();i++){
                model.removeRow(i);
            }
        }
    }

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        DefaultTableModel model = (DefaultTableModel) annoTab.getModel();
        TableColumn valueColumn = annoTab.getColumnModel().getColumn(1);
        CustomTableCellEditor customEditor = new CustomTableCellEditor();
        for (Entry<String, HashSet<String>> avar : Annotation.resultSet.entrySet()) {
            Object[] row = new Object[2];
            row[0] = avar.getKey();
            model.addRow(row);
            setUpValueColumn(valueColumn, customEditor, avar.getValue());
        }
        valueColumn.setCellEditor(customEditor);
    }

    public void setUpValueColumn(TableColumn sportColumn, CustomTableCellEditor customEditor, HashSet<String> values) {
        customEditor.addComboBox(new JComboBox(new DefaultComboBoxModel(values.toArray())));
        ComboBoxTableCellRenderer renderer = new ComboBoxTableCellRenderer();
        sportColumn.setCellRenderer(renderer);

    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         


    }                                        

    public static String readFile( String file ) throws IOException {
        BufferedReader reader = new BufferedReader( new FileReader (file));
        String         line = null;
        StringBuilder  sb = new StringBuilder();
        String         ls = System.getProperty("line.separator");

        while( ( line = reader.readLine() ) != null ) {
        sb.append( line );
        sb.append( ls );
        }
        return sb.toString();
    }

    public static void main(String args[]) 
    {
        Annotation.ScoreCalculator();


        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AnnotationGeneration().setVisible(true);
            }
        });        
    }

    static HashMap<String, String> annotation = new HashMap<String, String>();
    static Vector<String> value = new Vector<String>();
    JTextField feildArray[];

    private javax.swing.JTable annoTab;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;

}

AnnotationVar.java

public class AnnotationVar implements Comparator<AnnotationVar>, Comparable<AnnotationVar>{

    public AnnotationVar() {
        this.attribute = new String();
        this.values = new HashSet<String>();
        this.score = 0.0f;
    }

    public AnnotationVar(String attribute) {
        this();
        this.attribute = attribute;
    }

    public AnnotationVar(String attribute, HashSet<String> values, float score){
        this();
        this.attribute = attribute;
        this.values = values;
        this.score = score;
    }

    private String attribute;
    private HashSet<String> values;
    private float score;

    public String get_attribute() {
        return this.attribute;
    }

    public HashSet<String> get_values() {
        return this.values;
    }

    public AnnotationVar set_values(HashSet<String> values) {
        this.values = values;
        return this;
    }

    public AnnotationVar set_score(float score){
        this.score = score;
        return this;
    }

    @Override
    public int compare(AnnotationVar o1, AnnotationVar o2) {
        return -Float.compare(o1.score, o2.score);
    }

    @Override
    public int compareTo(AnnotationVar av){
      return -Float.compare(this.score, av.score);
    }

    @Override
    public String toString() {
        return this.attribute + " " + this.values.toString() + " " + Float.toString(this.score);
    }
}

Annotation.java

public class Annotation {

    public static HashMap<String, AnnotationVar> anotVarMap = new HashMap<String, AnnotationVar>();
    public static HashMap<String, HashSet<String>> resultSet = new HashMap<String, HashSet<String>>();


    private static float contVal(String b, String c) {
        ...
    }

    private static float contVal2(String b, String c) {
        ...
    }
    private static float querVal(String a1) {
        ...
    }
    private static void valueGen() throws IOException {
        ...
    }

    ArrayList<AnnotationVar> attList = new ArrayList<AnnotationVar>(anotVarMap.values());
    Collections.sort(attList);


        for(AnnotationVar att: attList) {
            resultSet.put(att.get_attribute(), new HashSet<String>());
        }

        while (st.hasMoreTokens()) {    
            String tok = st.nextToken();

            System.out.println(tok);
            for(AnnotationVar avar : anotVarMap.values()) {

                if(avar.get_values().contains(tok)) {
                    System.out.println(avar);
                    //attrib = avar.get_attribute();
                    resultSet.get(avar.get_attribute()).add(tok);
                }

            }

        }  
        System.out.println("Updated collection :"+resultSet);
    }

    public static void ScoreCalculator() {

        try 
        {
            DBconnection con = new DBconnection();
            PreparedStatement statement;
            String x = "select count(*) from queryvalues";
            statement = con.getConnection().prepareStatement(x);
            ResultSet rs = statement.executeQuery();
            while (rs.next()) 
            {
                String name = rs.getString(1);
                int num = Integer.valueOf(name);
                for(int i=1;i<num+1;i++)
                {
                    String y = "select attribute from queryvalues where slno = ?";
                    statement = con.getConnection().prepareStatement(y);
                    statement.setInt(1, i);
                    ResultSet rs2 = statement.executeQuery();   
                    while (rs2.next()) 
                    {
                        String a1 = rs2.getString(1);
                        anotVarMap.put(a1,new AnnotationVar(a1));
                        //System.out.println(a1);
                        String a = "D:/test5.txt" ;
                        String abc = AnnotationGeneration.readFile(a);
                        StringTokenizer st = new StringTokenizer(abc);

                        float cv1 = 1;
                        float cv4 =1;
                        while (st.hasMoreTokens()) 
                        {

                            String tok = st.nextToken();
                            float cv0 = contVal(a1,tok);
                            cv1 = cv0*cv1;
                            float cv3 = contVal2(a1,tok);
                            cv4=cv3*cv4;  
                        }
                        float cv = cv1/cv4;                    
                        float qv1 = querVal(a1);
                      //System.out.println("querying value =" + qv1);
                      //System.out.println("content value =" + cv);
                        float score = cv*qv1;
                      //System.out.println("score of " + a1 + "=" + score);
                       String z = "INSERT into qvtemp(attribute,score) VALUES (?,?) ON DUPLICATE KEY UPDATE score = VALUES(score)";
                         statement = con.getConnection().prepareStatement(z);
                        statement.setString(1,a1);
                        statement.setFloat(2,score);
                        statement.executeUpdate(); 
                        anotVarMap.get(a1).set_score(score);
                    }    
                }  

                ArrayList<AnnotationVar> attList = new ArrayList<AnnotationVar>(anotVarMap.values());
                Collections.sort(attList);

                System.out.println(anotVarMap);
                System.out.println(attList);
            }

            valueGen();
            System.out.println(anotVarMap);
        } catch (SQLException | IOException ex) {
            Logger.getLogger(AnnotationGeneration.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
Madhan

Then you have to define you custom TableCellEditor as follows.Anyhow I comeup with the following. where for everyrow I store the combobox values and returning the values based on the row

     private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
        DefaultTableModel model = (DefaultTableModel) annoTab.getModel();
        TableColumn valueColumn = annoTab.getColumnModel().getColumn(1);
        CustomTableCellEditor customEditor = new CustomTableCellEditor();
        for (Entry<String, HashSet<String>> avar : Annotation.resultSet.entrySet()) {
            Object[] row = new Object[2];
            row[0] = avar.getKey();
        //Edit to set the first value in hashset as defaultvalue;
            row[1]=avar.getValue().iterator().next();

            model.addRow(row);
            setUpValueColumn(valueColumn, customEditor, avar.getValue());
        }
        valueColumn.setCellEditor(customEditor);
    }

    public void setUpValueColumn(TableColumn sportColumn, CustomTableCellEditor customEditor, HashSet<String> values) {
        customEditor.addComboBox(new JComboBox(new DefaultComboBoxModel(values.toArray())));
        ComboBoxTableCellRenderer renderer = new ComboBoxTableCellRenderer();
        sportColumn.setCellRenderer(renderer);
    }

The customCellEditor

class CustomTableCellEditor extends AbstractCellEditor implements TableCellEditor {

    private TableCellEditor editor;
    private HashMap<Integer, JComboBox> listDetails = new HashMap<>();

    public void addComboBox(JComboBox combobox) {
        listDetails.put(listDetails.size(), combobox);
    }

    public void setComboBoxForRow(int row, JComboBox combobox) {
        listDetails.put(row, combobox);
    }

    @Override
    public Object getCellEditorValue() {
        if (editor != null) {
            return editor.getCellEditorValue();
        }
        return null;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        if (listDetails.containsKey(row)) {
            editor = new DefaultCellEditor(listDetails.get(row));
        }
        return editor.getTableCellEditorComponent(table, value, isSelected, row, column);
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Adding items to combo box in a table in netbeans

From Dev

How to add data table items in a combo box?

From Dev

Adding items from a database to a combo box and a text box

From Dev

Excel VBA adding items to combo box without repeated items

From Dev

Excel VBA adding items to combo box without repeated items

From Dev

Adding table names in oracle database to combo box in visual studio 2012

From Dev

How to send these items in the combo box

From Dev

Set items to Combo Box in JAVA

From Dev

Combo box custom items and data bound items

From Dev

Combo box custom items and data bound items

From Dev

Multiplying text field with combo box Netbeans

From Dev

How to add BOTH static values and records from a table as list items to a combo box in VBA

From Dev

How to Open Drop down (combo items) of Combo Box on KeyDown Event?

From Dev

How to Open Drop down (combo items) of Combo Box on KeyDown Event?

From Dev

Unselectable items in a Combo Box in an Excel VBA

From Dev

How to add items from combo box into array

From Dev

Edit Win32 combo box items

From Dev

adding a value to my combo box using query

From Dev

adding a value to my combo box using query

From Dev

Adding record via not in list event of combo box

From Dev

Source for a combo box differs when adding a record

From Dev

JList adding and removing items (Netbeans)

From Dev

Remove Items from Collection in a loop (Combo Box items)

From Dev

JavaFX: Combo box focus issue in table view

From Dev

Bind combo box from table with two columns

From Dev

Get data from table with combo box (Codeigniter)

From Dev

Filter a table based on a combo box value

From Dev

How to add scroollbar to combo box items in c#

From Dev

Combo Box Can't be clicked after remove All Items

Related Related

  1. 1

    Adding items to combo box in a table in netbeans

  2. 2

    How to add data table items in a combo box?

  3. 3

    Adding items from a database to a combo box and a text box

  4. 4

    Excel VBA adding items to combo box without repeated items

  5. 5

    Excel VBA adding items to combo box without repeated items

  6. 6

    Adding table names in oracle database to combo box in visual studio 2012

  7. 7

    How to send these items in the combo box

  8. 8

    Set items to Combo Box in JAVA

  9. 9

    Combo box custom items and data bound items

  10. 10

    Combo box custom items and data bound items

  11. 11

    Multiplying text field with combo box Netbeans

  12. 12

    How to add BOTH static values and records from a table as list items to a combo box in VBA

  13. 13

    How to Open Drop down (combo items) of Combo Box on KeyDown Event?

  14. 14

    How to Open Drop down (combo items) of Combo Box on KeyDown Event?

  15. 15

    Unselectable items in a Combo Box in an Excel VBA

  16. 16

    How to add items from combo box into array

  17. 17

    Edit Win32 combo box items

  18. 18

    adding a value to my combo box using query

  19. 19

    adding a value to my combo box using query

  20. 20

    Adding record via not in list event of combo box

  21. 21

    Source for a combo box differs when adding a record

  22. 22

    JList adding and removing items (Netbeans)

  23. 23

    Remove Items from Collection in a loop (Combo Box items)

  24. 24

    JavaFX: Combo box focus issue in table view

  25. 25

    Bind combo box from table with two columns

  26. 26

    Get data from table with combo box (Codeigniter)

  27. 27

    Filter a table based on a combo box value

  28. 28

    How to add scroollbar to combo box items in c#

  29. 29

    Combo Box Can't be clicked after remove All Items

HotTag

Archive