swing跳转另一个界面
时间: 2023-08-27 15:05:40 浏览: 37
要在Swing中实现跳转到另一个界面,可以使用以下步骤:
1. 创建一个JFrame对象,作为目标界面。
2. 在源界面的事件处理方法中,创建目标界面的实例对象。
3. 调用源界面的setVisible(false)方法,将源界面隐藏。
4. 调用目标界面的setVisible(true)方法,将目标界面显示。
下面是一个简单的示例代码,演示如何在Swing中实现界面跳转:
```
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame extends JFrame {
public MainFrame() {
JButton button = new JButton("跳转到目标界面");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TargetFrame targetFrame = new TargetFrame();
setVisible(false);
targetFrame.setVisible(true);
}
});
add(button);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
class TargetFrame extends JFrame {
public TargetFrame() {
JLabel label = new JLabel("这是目标界面");
add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
}
}
```
这个示例代码中,我们在MainFrame类中创建了一个“跳转到目标界面”的按钮,并为它添加了一个ActionListener。在ActionListener中,我们创建了TargetFrame的实例对象,并将当前界面隐藏,将目标界面显示。如果需要返回到源界面,只需要在目标界面中添加返回按钮,并在其事件处理方法中实现返回逻辑即可。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)