溫馨提示×

swing跳轉(zhuǎn)另一個界面怎么實現(xiàn)

小億
273
2023-12-07 13:07:56
欄目: 智能運維

要實現(xiàn)swing跳轉(zhuǎn)到另一個界面,可以使用以下步驟:

  1. 創(chuàng)建一個新的JFrame對象,作為要跳轉(zhuǎn)到的界面。
  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("跳轉(zhuǎn)");
        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();  // 釋放當前界面資源,如果不需要再回到當前界面可以調(diào)用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);
    }
}

在上面的示例中,點擊主界面上的按鈕會隱藏主界面,并顯示另一個界面。另一個界面的代碼和主界面類似,只是界面上的內(nèi)容可以根據(jù)需求進行調(diào)整。

0