For glasspane purposes, why are input elements in Swing seemingly not considered part of a JPanel?

余生长醉 提交于 2019-12-02 02:44:43

问题


By input elements I mean things like JSpinners and JComboxBoxes. My glasspane is passed a JPanel containing JSpinners, JComboBoxes and for the most part, JLabels. The glasspane has a MouseListener attached. The surprising thing is that mouseEntered is called upon the mouse cursor leaving the input elements and hovering over the other parts or empty space of the JPanel! Is this normal behaviour? How can I get the input elements to be considered part of the JPanel for Glasspane purposes?

Here is a screenshot of my UI with its input elements and jLabels.

Here is an example piece of Code:

import javax.swing.*;

public class DialogTest {
    public DialogTest() {
        JPanel dialogPanel = new JPanel();
        SpinnerModel edgeModel = new SpinnerNumberModel(1, 1, 9, 1);
        JSpinner edgeSpn = new JSpinner(edgeModel);
        dialogPanel.add(edgeSpn);

        JDialog initialDialog = new JDialog(new JFrame(), "Test", true);
        initialDialog.setContentPane(dialogPanel);
        initialDialog.pack();
        glass = new GlassComponent(dialogPanel);
        initialDialog.setGlassPane(glass);
        glass.setOpaque(false);
        glass.setVisible(true);
    initialDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    initialDialog.setVisible(true);
    }
}

public class GlassComponent implements MouseListener {
   JPanel c;
   public GlassComponent(JPanel c) {
       this.c = c;
       this.c.addMouseListener(this);
   }

   ...
   public mouseEntered(MouseEvent e) {
       System.out.println("Entered JPanel");
   }    
}

By way of explanation, my goal is to eventually use the GlassPane to block input for those elements marked with the prohibition sign. However, given that the mouseListener assigned to the dialogPanel is seemingly generating new events upon leaving the input elements, I may have some difficulties achieving this.


回答1:


You can forward mouse events to the underlying components, as shown in The Glass Pane demo's method, redispatchMouseEvent().




回答2:


You appear to be using glasspane in a way that I feel it shouldn't be used.

As far as I know, a glasspane typically shouldn't be holding components at all but rather cover over the top-level window and then can act as a gate-keeper for the components that are below it, all held by the top level window's contentPane.




回答3:


  • you can use GlassPane for overlay required Container or JComponent by @camickr, or my questions based on his code here or here,

  • another suggestion could be use JLayer (required Java7 for Java6 is there JXLayer)



来源:https://stackoverflow.com/questions/9707470/for-glasspane-purposes-why-are-input-elements-in-swing-seemingly-not-considered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!