将项添加到netbeans中的表中的组合框

时间:2015-06-21 14:10:47

标签: java swing netbeans jtable jcombobox

我有一个表,其中一列需要包含组合框。

当我运行以下代码时,我会在每个单元格中获得组合框,但这些项目不会添加到其中。当我尝试使用system.out.println(val)打印项目时,它们会被打印,但它们不会被添加到组合框中。

我该怎么做?

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

完整代码

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

}

1 个答案:

答案 0 :(得分:1)

然后你必须按如下方式定义自定义TableCellEditor。无论如何,我想出了以下内容。对于每一行,我存储组合框值并根据行返回值

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

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