java两个界面传递参数_java 传值 两个窗口

展开全部

下面的代码演示了两种方法传递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);

}

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值