展开全部
下面的代码演示了两种方法传递x值到 B 窗口中,一种是通过 B 的构e68a84e8a2ad62616964757a686964616f31333365646239造方法,一种是通过 B 中的 x 的 setter 传递。import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
class A extends JFrame {
private int x = 10;
public A() {
this.setTitle("A");
this.setSize(300, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
JButton button = new JButton("Open B");
button.addActionListener(e -> {
// 通构造方法传递
B b = new B(this.x);
// 通过 setter 方法传递
b.setX(x);
b.setVisible(true);
});
this.add(button);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
class B extends JFrame {
private int x;
public B(int x) {
this.setTitle("B");
this.setSize(300, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setLayout(new FlowLayout());
this.x = x;
JButton button = new JButton("显示x的值");
button.addActionListener(e -> {
JOptionPane.showMessageDialog(this, x);
});
this.add(button);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
public class App {
public static void main(String[] args) {
new A().setVisible(true);
}
}