问题
I build a main class runs 5 classes, and make them able to pass string to each other. I just post main class + class 1 and 4.
Main class:
public class main {
public static void main(String[] args){
class4 c4 = new class4(c1);
class3 c3 = new class3(c4);
class2 c2 = new class2(c3);
c2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c2.setSize(200,100);
c2.setLocationRelativeTo(null);
c2.setVisible(true);
class1 c1 = new class1(c2);
c1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c1.setSize(200,100);
c1.setLocationRelativeTo(null);
c1.setVisible(true);
}
}
Class 1:
public class class1 extends JFrame{
private JButton jb;
private class2 c2;
public class1(class2 c2){
this();
this.c2 = c2;
}
public class1(){
super("");
setLayout(new FlowLayout());
jb = new JButton("click click");
add(jb);
jb.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
sayHi("Hi buddy");
}});
}
public void sayHi(String x){
c2.recieveHi(x);
}
public void recieveHi(String x){
System.out.println(x);
}
}
Class 5:
public class class4 {
private class1 c1;
public class4(class1 c1){
//this();
this.c1 = c1;
}
public void recieveHi(String x){
System.out.println(x);
killMessenger();
}
public void killMessenger(){
String s = "back to class 1";
c1.recieveHi(s);
}
}
Class 1 pass String to class2, which pass String to class 3 etc.. When class4 recieve String, i need to pass a String to class1.. As you can see in my main class, i need to bind them e.g
class 1 c1 = new class1(c2);
Doing it with class4 c4 = new class4(c1) doesn't work, because class1 isn't made yet. There will always be an lose end to it, so there might be a method to fix it.
回答1:
You could have a setter method, so you don't pass c1 in the constructor but after the class1 instance is created. In your class4 class
public void setClass1Object(class1 pC1) {
this.c1 = pC1;
}
来源:https://stackoverflow.com/questions/21220273/java-chain-classes