如何使用数据库中的信息将jcombobox步进到数组

问题描述

我在Java中有一个图形显示,其中我有一个JFrame,其中Jtable的Jtable的行数为10,行数为4,第三列是一个jcomboBox,它会转到DB来为列2中输入的值获取属于列3的值和该行的1个。 这是代码

      //JCOMBOBox CREATED
        TableColumn sportColumn = table.getColumnModel().getColumn(3);
        JComboBox comboBox = new JComboBox();
        sportColumn.setCellEditor(new DefaultCellEditor(comboBox));

comboBox.addMouseListener(new MouseAdapter() {
  public void mousepressed(MouseEvent event) {
  
      try{     
    
            int comboBoxRow = table.getSelectedRow();
            String OFNUPK = (String) table.getValueAt(comboBoxRow,1);
            String TFCCMP = (String) table.getValueAt(comboBoxRow,2);

            // Se o valor for nulo ou não inteiro isto vai atirar erro
            int OFNUP = Integer.parseInt(OFNUPK);

            // Verificar se o valor é válido
            if (TFCCMP != null && !TFCCMP.isEmpty()) {
            Connection con = DriverManager.getConnection("jdbc:as400://" + host,user,pwd);
            // create new statement from connection
            Statement stmt = con.createStatement();

            // Se puderes aqui usa prepared statements como te mostrei ontem
            String s = "SELECT disTINCT a.TFCPAI FROM $$CLI00F55.FOFFAN a,SICGA00F55.FORFAB f WHERE "
            + "a.TFCCMP = '" + TFCCMP + "' AND f.OFNUPK = " + OFNUP +" AND f.OFNUPK = a.TFSNOF";

            ResultSet rs = stmt.executeQuery(s);
            //APAGAR OS DADOS ANTERIORES
           while(rs.next())
            {
                comboBox.addItem(rs.getString(1));
            }

在同一行中单击JcomboBox时,添加两个相同的值时遇到两个问题。 并且在下一行中,也会出现在上一行中的数据。

如果您需要更多信息,请发表评论。 谢谢!

解决方法

您不需要使用任何侦听器。您需要在TableCellEditor中覆盖方法localhost:5432

kubectl port-forward <service-name> 5432:5432

请注意,您还需要确保TableModel具有适当的getTableCellEditorComponent()方法。我猜您正在使用DefaultTableModel。如果是这样,则它已经具有适当的JComboBox comboBox = new JComboBox(); sportColumn.setCellEditor(new DefaultCellEditor(comboBox)) { public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) { JComboBox comboBox = (JComboBox) editorComponent String OFNUPK = (String) table.getValueAt(row,1); String TFCCMP = (String) table.getValueAt(row,2); // Se o valor for nulo ou não inteiro isto vai atirar erro int OFNUP = Integer.parseInt(OFNUPK); // Verificar se o valor é válido if (TFCCMP != null && !TFCCMP.isEmpty()) { Connection con = DriverManager.getConnection("jdbc:as400://" + host,user,pwd); // create new statement from connection Statement stmt = con.createStatement(); // Se puderes aqui usa prepared statements como te mostrei ontem String s = "SELECT DISTINCT a.TFCPAI FROM $$CLI00F55.FOFFAN a,SICGA00F55.FORFAB f WHERE " + "a.TFCCMP = '" + TFCCMP + "' AND f.OFNUPK = " + OFNUP +" AND f.OFNUPK = a.TFSNOF"; ResultSet rs = stmt.executeQuery(s); //APAGAR OS DADOS ANTERIORES while(rs.next()) { comboBox.addItem(rs.getString(1)); } } }); 方法,因此您无需在此执行任何操作。

也不要忘记关闭数据库连接以及处理任何可能引发的setValueAt()。也许考虑使用setValueAt()而不是SQLException