netbeans 中出现重复的 jframes

duplicate jframes appear in netbeans

我正在将数据从 frame1 中的一个 jtable 传输到 frame2 中的另一个 jtable。 问题是,每次我 select 我的第一个 table 的一行并按下按钮(将其传输到另一个 table)时,另一个框架弹出并且数据被送入第一排。我希望所有 selected 数据都在同一个 table.

我知道我的代码写错了,但我不知道正确的解决方案!这是我的代码

 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    int row = jTable2.getSelectedRow();        
    String a1=jTable2.getModel().getValueAt(row, 1).toString();
    String a2=jTable2.getModel().getValueAt(row, 4).toString();
    String a3=jTable2.getModel().getValueAt(row, 21).toString();
    String a4=jTable2.getModel().getValueAt(row, 5).toString();
    String a5=jTable2.getModel().getValueAt(row, 22).toString();
     NewJFrame2 fr2 = new NewJFrame2();
     fr2.gencode(a1, a2, a3, a4, a5);
        //this.dispose();
        fr2.setVisible(true);
}

这是另一个框架

public NewJFrame2() {
    initComponents();
}
        int i=0;
        public void gencode(String a1, String a2, String a3, String a4, String a5){
            System.out.print(i);
            i++;
        jTable1.setValueAt(a1, i, 0);
        jTable1.setValueAt(a2, i, 1);
        jTable1.setValueAt(a3, i, 2);
        jTable1.setValueAt(a4, i, 3);
        jTable1.setValueAt(a5, i, 4);

   }

问题是您正在按钮单击事件中创建新框架

 NewJFrame2 fr2 = new NewJFrame2(); //here is the problem

在你的 frame one 中声明一个实例变量 frame2

class One{
  NewJFrame2 fr2;
}

并在需要时初始化它,但只需一次 并在操作方法中使用

  if(fr2==null){
      fr2=new  NewJFrame2(); //initialize if it's null
  }
  fr2.gencode(a1, a2, a3, a4, a5);
NewJFrame2 fr2=null; //class level variable
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        int row = jTable2.getSelectedRow();        
        String a1=jTable2.getModel().getValueAt(row, 1).toString();
        String a2=jTable2.getModel().getValueAt(row, 4).toString();
        String a3=jTable2.getModel().getValueAt(row, 21).toString();
        String a4=jTable2.getModel().getValueAt(row, 5).toString();
        String a5=jTable2.getModel().getValueAt(row, 22).toString();
        //create instance when not initiated
        if(fr1==null){
            fr2 = new NewJFrame2();
        }
         fr2.gencode(a1, a2, a3, a4, a5);
            //this.dispose();
            fr2.setVisible(true);
    }

将fr2设为class级变量,未启动时创建实例