Reputation: 63
I want to transfer a variable value of type List (variable name is seznamRacunov) from one class to another.
Class 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){}
}
}
Class 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){}
}
Method seznamRacunov.add(potRacuna);
store a value into seznamRacunov in Class 1, but the value of list does not pass in class 2 where I called getter. What is wrong?
Upvotes: 0
Views: 2103
Reputation: 213203
Method seznamRacunov.add(potRacuna); store a value into seznamRacunov in Class 1, but the value of list does not pass in class 2 where I called getter.
Thats because, you are trying to get()
your List
without even calling the method - showDailog()
which in turn invokes your add()
method to populate list.
Make sure, you invoke this method - showDailog()
to populate the list, before you actually fetch the List
with get
method
Or, it would be better, if you add a constructor
to your class, which does the task of initializing
your List
. Then you can create an instance using that constructor
and thus you won't have any problem.
PS: - You should always have at least a 0-arg constructor
to initialize your fields, rather than letting
compiler handle this task for you.
And one more thing, you should never, ever engulp your exception by having an empty
catch block. Else there is no point in catching them. Add a printStackTrace()
call instead.
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
declaration in your first class. You are using generic type List
on LHS, and a Raw type ArrayList
on the RHS. Its something that you should avoid.Have Generic
type on both the sides: -
private List<String> seznamRacunov = new ArrayList<String>();
Upvotes: 1