i hope that i mean my words. i have a class like this:
public class MainClass extends JFrame{
private JLabel mainlabel;
private SampleClass sample=new SampleCalss();
public void intital(){
mainlabel=new JLabel("Main");
sample.setMethod(getLabel());
//
//some code
//
add(mainlabel);
}
public static void main(){
intital();
}
public JLabel getLabel(){
return mainlabel;
}
}
and other class like this:
public class SampleClass extends JFrame{
private JButton button=new JButton("Change");
private JLabel sLabel;
public SampleClass(){
//somecode
//
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
sLabel.setText("Sample text set");
}
});
add(jButton);
}
public void setMethod(JLabbel l){
sLabel=l;
}
}
is this a true way to access mainlabel
and change its value from other class(in this sample code in class SampleClass
) is there a better or right solution?
note that MainClass
is class that has main
method.
You can use Java Reflection to access the private variables and change the values.
http://download.oracle.com/javase/tutorial/reflect/member/fieldValues.html
Why not expose the mainlabel through setMainLabel ?
The problem with your method is if MainClass ever changes its JLabel (by creating a new one), SampleClass still has a reference to the old one. You can give SampleClass a reference to MainClass via the constructor or a setter method:
And whenever you need to access MainClass' label, call its getter method:
The correct way to access a private variable from another class is with getter and setter methods. Otherwise, you should have made that variable public.
That is:
However, it is a bad practice to return private data directly - that allows external code to modify your private state. In general, you should return a copy of your private data so that external code can't mess with the internals of your class. But if you need external code to call methods on your private data, then you should probably be providing manipulation methods in your class, rather than directly exposing private data.
You probably really want to create methods like
setText()
andgetText()
in your main class, and then call thesetText()
andgetText()
methods onmainlabel
. However, you need to be careful with this, as you might be inclined to replicate every single method defined byJLabel
in your class. That would tightly couple both your class and its consumers wit theJLabel
implementation. If you choose to replace theJLabel
with something else in the future, it will take a lot of work to unwind the coupling you've created.In class, private variables can be used without explicitly calling getter method for private variable.
So it would be like below for the first class
And your assumption for setting private variable in different class by using setter method is correct.