2013-08-23 58 views
0

我的問題是關於java swing frame。我有一個2 jFrame。 jFrame1和jFrame2。在jframe 1中有一個jbutton,所以當用戶單擊我想要關注幀2(第2幀已經加載到應用程序中)的jbutton時,不關閉frame1。請幫助做到這一點將焦點設置爲其他jframe

+3

使用模式對話框!此外,看到這個問題[使用多個JFrames,好/壞實踐?](http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice) –

+0

唐'不知道JDialog需要模態,但是你應該使用JDialog作爲子窗口。 – camickr

回答

0

您可以使用Window.toFront()使當前幀前:

import java.awt.Window; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

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

public class MyFrame extends JFrame implements ActionListener { 
    public MyFrame(String title) { 
     super(title); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     JButton button = new JButton("Bring other MyFrame to front"); 
     button.addActionListener(this); 
     add(button); 
     pack(); 
     setVisible(true); 
    } 

    public static void main(String[] args) { 
     new MyFrame("1"); 
     new MyFrame("2"); 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     for (Window window : Window.getWindows()) { 
      if (this != window) { 
       window.toFront(); 
       return; 
      } 
     } 
    } 
} 
+0

這是對錯誤問題的正確答案。看評論。 –