Java, how to close the program and go to the boot from the GUI

I made a regular window with an image. I was wondering how to make the "Click here to start" button, which, when clicked, will close the program and start another program.

+1
source share
3 answers

I would start by looking at How to use buttons , and also take a look at How to use CardLayout

This will allow you to have one window and reduce the amount of switch code you need

import java.awt.CardLayout; import java.awt.EventQueue; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class SimpleDemo { public static void main(String[] args) { new SimpleDemo(); } public SimpleDemo() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } final CardLayout cardLayout = new CardLayout(); final JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(cardLayout); JPanel startPanel = new JPanel(new GridBagLayout()); JButton startButton = new JButton("Start"); startPanel.add(startButton); startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cardLayout.show(frame.getContentPane(), "game"); } }); JLabel game = new JLabel("Game On", JLabel.CENTER); frame.add(startPanel, "start"); frame.add(game, "game"); cardLayout.show(frame.getContentPane(), "start"); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } 
+5
source

To hide the window, but keep the resources behind it, use JFrame.setVisible(false) . To completely get rid of it, use the dispose() method.

To start a new window, use code similar to what you used to start your first window.

There are many resources available on the Internet and on this website to help you learn how to create a button, including your own Oracle site :

+2
source

Just call main (String []) in your second program to run it. If the current one is no longer required, call the dispose () function on your frame.

The classes of your second program must be in the class. This can be easily arranged by writing suitable bash / bat loading scripts, or you can link all classes in one jar.

0
source

All Articles