スイングで別の画面に遷移するにはどうすればいいの?
Swing において別の画面に移動するには、次の手順を実行できます。
- フレームとして遷移先の画面を作成する。
- この画面のイベント処理内で、setVisible(false)を使います。
- 新たな画面を表示するには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);
}
}
上記の例では、メイン画面のボタンを押すと、メイン画面は非表示となり、別の画面が表示されます。別の画面のコードはメイン画面と似ていますが、画面の内容は必要に応じて調整できます。