编程语言
首页 > 编程语言> > java-出于玻璃窗格的目的,为什么Swing中的输入元素似乎不被视为JPanel的一部分?

java-出于玻璃窗格的目的,为什么Swing中的输入元素似乎不被视为JPanel的一部分?

作者:互联网

输入元素是指JSpinners和JComboxBoxes之类的东西.我的玻璃窗格通过了一个包含JSpinners,JComboBoxes和大多数情况下的JLabels的JPanel.玻璃窗格上附加了MouseListener.令人惊讶的是,在鼠标光标离开输入元素并悬停在JPanel的其他部分或空白上时会调用mouseEntered!这是正常行为吗?出于Glasspane的目的,如何将输入元素视为JPanel的一部分?

这是我的UI的屏幕截图,其中包含输入元素和jLabel.

这是一段示例代码:

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");
   }    
}

作为解释,我的目标是最终使用GlassPane阻止输入带有禁止符号的元素.但是,考虑到分配给dialogPanel的mouseListener似乎在离开输入元素时会生成新事件,因此实现此目标可能会有些困难.

解决方法:

您可以将鼠标事件转发到基础组件,如The Glass Pane演示的方法redispatchMouseEvent()中所示.

标签:java,swing,jpanel,glasspane
来源: https://codeday.me/bug/20191012/1900210.html