有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在netbeans中触发事件

我目前正在用netbeans编写我的第一个GUI应用程序。在我的JFrame中有一个JComboBox和一个JTable

当在ComboBox中选择一个项目时,我想向JTable中添加行,但是在什么情况下我应该放置填充Jtable的代码


共 (2) 个答案

  1. # 1 楼答案

    您需要将侦听器添加到组合框中,然后获取jtable的模型并添加行

    例如:

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Selected: " + comboBox.getSelectedItem());
            System.out.println(", Position: " + comboBox.getSelectedIndex());
    
            DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    
            model.addRow(row);
            
        }
    };
    
  2. # 2 楼答案

    您可以使用JCOMBOBOX的ActionPerformed事件或ItemStateChanged事件

    You can right click on the JCOMBOBOX and do the following

       public void populateTable(JTable jt, String value) {
            DefaultTableModel dtm = (DefaultTableModel) jt.getModel();
            int rowCount = jt.getRowCount();
            for (int i = rowCount - 1; i >= 0; i ) {
                dtm.removeRow(i);
            }
            Object data[] = new Object[1];
            data[0] = value;
            dtm.addRow(data);
    
        }
        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:
            String selValue =(String) jComboBox1.getSelectedItem();
            populateTable(jTable1, selValue);
        }
    

    输出结果如下: Output