2011-04-23 113 views
5

我在java中構建了一個小型的GUI遊戲,並且在某些時候我正在使用glassPane來暫時阻止所有的鼠標輸入。我之前使用過glassPane,沒有任何問題,但這次它不會阻止鼠標輸入。因此,我仍然可以在啓用glassPane時按下駐留在contentPane上的按鈕,我確定它已啓用,因爲我可以看到我在其上繪製的內容。glassPane沒有阻止輸入

這裏是一小段的可運行代碼的顯示問題:

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Toolkit; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 


public class GuiGame { 

    private JPanel contentPane; 
    private JButton button; 
    private JFrame frame; 
    private JPanel glassPane; 
    private Dimension screenSize; 

    public static void main(String[] args) { 
     GuiGame gui = new GuiGame(); 
     gui.createGUI(); 
    } 

    public void createGUI() 
    { 
     frame = new JFrame("BadGuiGame!"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setResizable(false); 
     screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
     contentPane = new JPanel(); 
     contentPane.setPreferredSize(new Dimension(400, 400)); 
     contentPane.setBackground(Color.WHITE); 
     contentPane.setLayout(null); 
     frame.setContentPane(contentPane); 
     frame.pack(); 

     glassPane = new JPanel(); 
     glassPane.setOpaque(false); 
     glassPane.setLayout(null); 
     JLabel glassLabel = new JLabel("Glass Enabled"); 
     glassLabel.setBounds(160, 50, 80, 20); 
     glassPane.add(glassLabel); 
     frame.setGlassPane(glassPane); 

     int buttonWidth = frame.getWidth()/2; 
     int buttonHeight = frame.getHeight()/4; 
     int xButton = (frame.getWidth() - buttonWidth)/2; 
     int yButton = frame.getHeight()/2; 
     button = new JButton("NEXT LEVEL!"); 
     button.setFocusable(false); 
     button.setEnabled(true); 
     button.setBounds(xButton, yButton, buttonWidth, buttonHeight); 
     contentPane.add(button); 

     int x = (screenSize.width - frame.getWidth())/2; 
     int y = (screenSize.height - frame.getHeight())/2; 
     frame.setLocation(x, y); 
     frame.setVisible(true); 
     glassPane.setVisible(true); 
    } 
} 
+2

+1 [SSCCE](http://sscce.org/) – AbdullahC 2011-04-23 01:24:51

回答

1

我會嘗試加入的MouseListener您glassPane和所有MouseEvents消耗的情況下,如

public void mouseClicked(MouseEvent e) { 
    e.consume(); 
} 
+1

謝謝!這工作,我甚至不需要'comsume()'方法。雖然它確實造成了一個新問題。我在glassPane上有一個JCombobox,並且由於我添加了mouselisteners,因此我無法滾動列表或使用鼠標選擇列表中的某些內容。 – Jesse 2011-04-23 09:46:49