I got class A which, after button is clicked:
if (source == buttonA){
new classB(this);
}
moreover, class A has function named
function(int a);
In class B I've got
public class classB extends JFrame implements ChangeListener {
public classB(A a) {
public void stateChanged(ChangeEvent e){
JSlider source = (JSlider)e.getSource();
tmp = source.getValue();
a.function(tmp);
}
}
}
But a cannot be resolved. How can I achieve that in other way?
You should change classB
to this:
public class classB extends JFrame implements ChangeListener {
private A a;
public classB(A a) {
this.a = a;
}
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
int tmp = source.getValue();
a.function(tmp);
}
}
Explanation
A couple of things were wrong with this class. Firstly the nested stateChanged
function in the constructor. Taking this out, meant that classB
needed a reference to class A
, that's why it needed a private A a;
field, and needed to be set in the constructor. Also, variable tmp
was not declared, always declare a variable before using it.
using this would have worked as well:
int tmp; //<-- variable declared, you can now assign a value to it.
tmp = source.getValue();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.