2013-03-20 80 views
1

我用圖像製作了一個普通窗口。我想知道如何製作一個按鈕說「點擊這裏開始」,當按下這個按鈕將關閉程序並啓動另一個程序。Java如何關閉程序並從GUI移動到另一個

+2

你想在同一個程序中啓動另一個程序或啓動另一個窗口嗎? – HXCaine 2013-03-20 00:09:08

+0

定義*「將關閉程序並啓動其他程序」*?您正在執行外部進程還是嘗試打開另一個Java窗口? – MadProgrammer 2013-03-20 00:09:20

+0

對不起,我的意思是它會啓動我的代碼的第二位,這就像數學遊戲,所以你會提出另一個窗口 – TheEagle 2013-03-20 00:13:36

回答

5

我想先在看看How to use Buttons開始,也看看How to Use CardLayout

這將讓你有一個窗口和減少對你的塞康的轉換代碼,你需要

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); 
      } 
     }); 
    } 
+0

非常有幫助 – TheEagle 2013-03-20 00:31:45

2

要隱藏窗口但保留資源,請使用JFrame.setVisible(false)。要完全擺脫它,請使用dispose()方法。

要啓動新窗口,請使用與您用來啓動第一個窗口的代碼類似的代碼。

有很多資源可在網上和this website,這將有助於您瞭解如何創建一個按鈕,包括Oracle's own site

0

直接讓主量(字符串[]) d程序啓動它。如果當前不再需要,請在其框架上調用dispose()。

你的第二個程序的類必須在類路徑中。這可以通過編寫適當的bash/bat啓動腳本來安排,也可以將所有類捆綁到單個jar中。

相關問題