2015-11-22 38 views
-1

我正在學習線程,並且遇到問題。我試圖製作2個框架,一個是主框架,另一個將在點擊按鈕後顯示。我想在新框架運行時停止主框架。你們能幫助我一個非常簡單的例子嗎? (並且點擊按鈕後新框架也會關閉)。只有2幀,每個按鈕都足夠了。非常感激!爲新的JFrame創建新線程

+1

你必須[瞭解搖擺(http://docs.oracle.com/javase/tutorial/uiswing/)。特別是關於[對話框]的部分(http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html)。 – Seelenvirtuose

+0

我知道對話框,但我要求提供我的鬧鐘應用程序 – NerdyGuy

+0

您有什麼問題?你真的希望人們爲你寫代碼嗎?這樣的問題完全脫離了SO! – Seelenvirtuose

回答

4

您應該避免the use of multiple JFrames,改爲使用模態dialogsJOptionPane提供了一個很好的,很容易&這樣做的靈活方法。

下面是一個例子。當您單擊該按鈕時,對話框將出現在JFrame的頂部。主JFrame將不再可點擊,因爲JOptionPane.showMessageDialog()產生modal window

import java.awt.EventQueue; 
import java.awt.FlowLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 

public class Example { 

    public Example() { 

     JFrame frame = new JFrame(); 

     JButton button = new JButton("Click me"); 
     button.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent arg0) { 
       JOptionPane.showMessageDialog(frame, "I'm a dialog!"); 
      } 
     }); 

     frame.getContentPane().setLayout(new FlowLayout()); 
     frame.getContentPane().add(button); 

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 

    } 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new Example(); 
      } 
     }); 
    } 


} 

輸出:

enter image description here

+0

的範圍內進行,我喜歡使用gif –