2012-04-03 68 views
1

我從一個applet中調用2個jDialog。只要我從第一個對話框中選擇該選項,然後單擊確定按鈕,小程序窗口就會聚焦,第二個對話框將失去焦點。Jdialog沒有專注於IE9

該問題只發生在IE瀏覽器,並在Firefox和Chrome中正常工作。請參閱代碼片段。 (雖然我的全代碼中的實際問題只在IE9中出現,我不知道爲什麼,這不是在IE8工作在SSCCE)

public class SampleApplet extends Applet{ 

protected JButton countryButton = new JButton("Select"); 

public synchronized void init() 
{ 
    this.setBounds(new Rectangle(350,350)); 
    this.add(countryButton); 


    countryButton.addActionListener(new ActionListener(){ 

     public void actionPerformed(ActionEvent arg0) { 
      getCountries(); 
      getCountries();    
     } 

    }); 
} 

protected void getCountries() { 
    JPanel panel = new JPanel(new GridBagLayout()); 
    GridBagConstraints gbc = new GridBagConstraints(); 
    JComboBox CountriesCombo = new JComboBox(); 
    CountriesCombo.addItem("India"); 
    CountriesCombo.addItem("Japan"); 
    panel.add(CountriesCombo, gbc); 

    JOptionPane  optionPane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); 

    final JDialog dialog  = optionPane.createDialog(panel, "Select Countries"); 
    dialog.setModal(true); 

    dialog.addWindowListener (new WindowAdapter() 
    { 
     public void windowOpened (WindowEvent e) 
     { 
      dialog.requestFocus(); 
     } 
    }); 
    dialog.pack(); 
    dialog.setLocationRelativeTo(null); 
    dialog.setVisible(true); 
} 

}

HTML代碼:

<html> 
<head> 
    <title>Sample Code</title> 
</head> 
<body> 
    <applet code="SampleApplet.class" width="350" height="350"> 
    </applet> 

我可以在這方面得到一些幫助。

+1

然後我想你需要展示一些很好的構建[SSCCE](http://sscce.org/) – 2012-04-03 11:53:50

+0

我準備好了SSCCE,如何分享它 – 2012-04-03 18:33:13

+1

請確保編輯你的問題,與你的SSCCE一樣,就是這樣,用這個新的代碼取代以前的代碼。 – 2012-04-03 18:59:57

回答

0

這種行爲有可能取決於您正在運行applet的瀏覽器(並且看起來您已經證明了這一點),所以我會爲您提供嘗試在對話框(或組件內部)上調用requestFocus()和requestFocusInWindow()它)將焦點放到對話框中。

再一次 - 如果您在打開對話框之前(在setVisible(true)之前)請求焦點,它將會失敗,因爲對話框尚未顯示。如果你在setVisible(true)方法之後調用它 - 如果你的對話框(或OptionPane)是模態的 - 它只有在對話框關閉時纔會執行,所以它也沒有意義。您應該在對話框中添加一個WindowListener,並在打開對話框後請求焦點。

檢查這個例子:

public static void main (String[] args) 
{ 
    // Modal dialog 
    final JDialog dialog = new JDialog (); 
    dialog.setModal (true); 

    // Adding listener 
    dialog.addWindowListener (new WindowAdapter() 
    { 
     public void windowOpened (WindowEvent e) 
     { 
      dialog.requestFocus(); 
     } 
    }); 

    // Displaying dialog 
    dialog.setVisible (true); 
} 

儘管如此,dialog.requestFocus(這裏)是一個依賴於平臺的調用,它可能無法對焦/彈出你的對話框頂部其他打開的窗口。在所有Windows版本中,它應該可以正常工作。

你也可以嘗試使用dialog.toFront() - 這應該彈出對話框並將焦點傳遞給它。

+0

我已經嘗試在對話框對象上的setVisible方法後調用「requestFocus()」。我們是否需要調用requestFocus()和requestFocusInWindow()。 – 2012-04-03 08:52:44

+0

調用後者,***而不是***前者,就像編譯器警告強烈要求你做的那樣。 – 2012-04-03 09:05:07

+0

如果對話框是模態的,並且在setVisible之後調用這些方法,請注意它不起作用,因爲只有在關閉模式對話框後,此方法纔會返回。爲了確保對話需要關注,你需要調用requestFocus()。雖然它可能在各種操作系統上有所不同。 – 2012-04-03 09:16:08