swing

swing跳转另一个界面怎么实现

小亿
213
2023-12-07 13:07:56
栏目: 智能运维

要实现swing跳转到另一个界面,可以使用以下步骤:

  1. 创建一个新的JFrame对象,作为要跳转到的界面。
  2. 在当前界面的事件处理方法中,使用setVisible(false)隐藏当前界面。
  3. 使用setVisible(true)显示新的界面。

以下是一个简单的示例代码:

import javax.swing.*;

public class MainFrame extends JFrame {
    private JButton button;

    public MainFrame() {
        setTitle("主界面");
        setSize(300, 200);
        setLocationRelativeTo(null);

        button = new JButton("跳转");
        button.addActionListener(e -> jumpToAnotherFrame());

        JPanel panel = new JPanel();
        panel.add(button);
        add(panel);
    }

    private void jumpToAnotherFrame() {
        AnotherFrame anotherFrame = new AnotherFrame();
        setVisible(false);
        anotherFrame.setVisible(true);
        dispose();  // 释放当前界面资源,如果不需要再回到当前界面可以调用dispose()方法
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MainFrame mainFrame = new MainFrame();
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainFrame.setVisible(true);
        });
    }
}

import javax.swing.*;

public class AnotherFrame extends JFrame {
    public AnotherFrame() {
        setTitle("另一个界面");
        setSize(300, 200);
        setLocationRelativeTo(null);
    }
}

在上面的示例中,点击主界面上的按钮会隐藏主界面,并显示另一个界面。另一个界面的代码和主界面类似,只是界面上的内容可以根据需求进行调整。

0
看了该问题的人还看了