swing跳转另一个界面
时间: 2023-08-29 14:08:12 浏览: 42
在Swing中,可以使用JFrame和JPanel来实现跳转到另一个界面。以下是一个简单的示例代码:
```java
import javax.swing.*;
import java.awt.event.*;
public class MainFrame extends JFrame {
private JPanel panel1, panel2;
public MainFrame() {
// 初始化面板1
panel1 = new JPanel();
JButton btnToPanel2 = new JButton("跳转到面板2");
btnToPanel2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 切换到面板2
getContentPane().removeAll();
getContentPane().add(panel2);
getContentPane().validate();
getContentPane().repaint();
}
});
panel1.add(btnToPanel2);
// 初始化面板2
panel2 = new JPanel();
JButton btnToPanel1 = new JButton("返回面板1");
btnToPanel1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 切换到面板1
getContentPane().removeAll();
getContentPane().add(panel1);
getContentPane().validate();
getContentPane().repaint();
}
});
panel2.add(btnToPanel1);
// 设置窗口
setTitle("跳转示例");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setContentPane(panel1);
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
```
该示例中使用两个JPanel分别表示两个界面,通过按钮的ActionListener实现跳转。需要注意的是,在跳转时需要先将原面板上的组件全部移除,再添加新面板上的组件,并调用validate()和repaint()方法重新绘制窗口。
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)