0

我想将 List 类型的变量值(变量名为 seznamRacunov)从一个类转移到另一个类。

1级

public class UvoziRacun 
{
  private String potRacuna;
  private List<String> seznamRacunov = new ArrayList();

  public void setRacun(List<String> seznamRacunov)
  {
      this.seznamRacunov = seznamRacunov;
  }

  public List<String> getRacun()
  {
      return seznamRacunov;
  }

  public String getPotRacuna()
  {
      return potRacuna;
  }

  public void showDailog()
  {
      try
      {
        JFileChooser racun = new JFileChooser();
        racun.setCurrentDirectory(new File(""));

        racun.setFileFilter(new javax.swing.filechooser.FileFilter() 
        {
            public boolean accept(File f) 
            {
                return f.getName().toLowerCase().endsWith(".xml") || f.isDirectory();
            }
            public String getDescription() 
            {
                return "XML Datoteka";
            }
        });

        //racun.setMultiSelectionEnabled(true);
        int r = racun.showOpenDialog(new JFrame());

        if (r == JFileChooser.APPROVE_OPTION)
        {
            potRacuna = racun.getSelectedFile().getPath();
            seznamRacunov.add(potRacuna); //value is stored
        }
        //System.out.print("Racuni: " + seznamRacunov);
      }
      catch(Exception ex){}
  }
}

2 级

public class PrikaziRacune extends javax.swing.JFrame 
{
    UvoziRacun rac = new UvoziRacun();

    public PrikaziRacune() 
    {
        initComponents();

        try
        {
            System.out.print(rac.getRacun()); // value is null, why?
            //jLabel2.setText();
        }
        catch(Exception ex){}
}

方法seznamRacunov.add(potRacuna);将值存储到类 1 中的 seznamRacunov 中,但列表的值没有传递到我调用 getter 的类 2 中。怎么了?

4

1 回答 1

1

方法 seznamRacunov.add(potRacuna); 将值存储到类 1 中的 seznamRacunov 中,但列表的值没有传递到我调用 getter 的类 2 中。

那是因为,你get()甚至List没有调用你的方法来method - showDailog()调用你的add()方法来填充列表。

  • 确保在实际获取with方法showDailog()之前调用此方法 -填充列表Listget

  • constructor或者,如果您将 a 添加到您的课程中,它会更好地完成initializing您的任务List。然后您可以使用它创建一个实例,constructor因此您不会有任何问题。

PS : - 你应该总是至少有一个0-arg constructor来初始化你的字段,而不是letting编译器为你处理这个任务。

还有一件事,你永远不应该通过一个emptycatch 块来吞噬你的异常。否则,抓住他们是没有意义的。printStackTrace()改为添加呼叫。

 public PrikaziRacune() {
    initComponents();

    try
    {
        rac.showDailog();  // Will populate the list
        System.out.print(rac.getRacun()); // You can get the value here.
        //jLabel2.setText();
    }
    catch(Exception ex) {
        ex.printStackTrace();
    }
}
  • ArrayList另外,请在您的第一堂课中检查您的声明。您generic type List在 LHS上使用,Raw type ArrayList在 RHS 上使用。它是你应该避免的。

Generic两边都有类型:-

private List<String> seznamRacunov = new ArrayList<String>();
于 2012-10-18T09:01:17.677 回答