I makes three classes DataTransfer, RetrieveData and StudSAllR
two classes RetrieveData and StudSAllR
are JFrame Form
DataTransfer Class:
I have made a data member(Select) in DataTransfer class of variable integer and made two methods getSelect()
and setSelect(int Select1)
,the code is given below:
class DataTransfer {
int Select;
public void setSelect(int Select1){
Select=Select1;
}
public int getSelect(){
return Select;
}
}
RetrieveData Class:
In this class I have A two buttons jButton2
and jButton4
, under ActionListener of these two buttons both are making object of DataTransfer class and setting values by calling setSelect() method for set Select 0 & 1
1 in jButton2 and 0 in jButton4 and after setting values both buttons are pointing to the third class StudSAllR, the below is its code given:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
DataTransfer DT = new DataTransfer();
DT.setSelect(0);
System.out.println(DT.getSelect()+"RD");
StudSAllR.main(new String[0]);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
DataTransfer DT = new DataTransfer();
DT.setSelect(1);
System.out.println(DT.getSelect()+"RD");
StudSAllR.main(new String[0]);
}
StudSAllR Class:
Under this class also, I am making object of DataTransfer, now by calling getSelect method i m returning select value but,
The problem is that it returning only 0 value, either i press jButton2 or jButton4 it returns 0
I have also set System.out.println(DT.getSelect()+"RD");
in the ActionListener of both buttons returns value 1 for jButton2 and 0 for jButton4
and when i call this get method in class 3 it returns only zero please guys help!!
This is because the DataTransfer objects you construct in your action listeners for the buttons are local to those methods. Their lifetime is restricted to the scope of the method. If you want to use the set value in a different class, there are different ways.
Pass DataTransfer
object into a method of other class StudSAllR
, but then you cannot use main()
because main()
is supposed to accept only String... args
so create a new static method probably called processDataTransfer()
public static void processDataTransfer( String... args, DataTransfer dt )
{
int select = dt.getSelect();
}
Make Select
in DataTransfer
static and also make getSelect()
and setSelect(int select)
static, then you don't need to initialize the class in button's action listeners. Just do : DataTransfer.setSelect(1);
In your StudSAllR.main(String... args)
call getSelect()
as :
public static void main(String... args)
{
int select = DataTransfer.getSelect();
}
What to choose between 1, 2 really depends on your requirements.