Java GUI中窗体的跳转

文章展示了如何在JavaSwing中创建两个JFrame(Test1和Text2),并通过在Text2中的JButton按钮事件处理程序实现点击后跳转到Test1界面,并可选地隐藏当前的Text2窗口。关键代码包括设置按钮的动作监听器以及在事件中创建并显示新的JFrame实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分别创建两个JFrame文件

public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Test1 frame = new Test1();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Text2 frame = new Text2();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

添加点击后进行跳转的按钮:JButton (这里是在text2中点击后显示test1的界面)

对JButton按钮添加事件

 

 在事件中添加显示test1的语句

Test1 frame = new Test1();
frame.setVisible(true);

添加后:

public Text2() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JButton btnNewButton = new JButton("New button");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Test1 frame = new Test1();
				frame.setVisible(true);
			}
		});
		btnNewButton.setBounds(147, 93, 123, 29);
		contentPane.add(btnNewButton);
	}

运行text2,点击按钮即可显示test1

若要使点击button按钮后只显示test1,使text2不可见,在按钮事件中添加语句即可。

setVisible(false);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值