边框影响组件位置 java



所以我有一个具有内部边框的JPanel(它基于MouseEnter/MouseExit进行切换,作为一种翻转效果)。我还有一个JLabel。问题在于 JLabel 似乎相对于边框定位 - 而不是 JPanel 的实际边缘。因此,每当我将鼠标移到面板上时,标签都会在几个像素上移动。我希望它保持静止。

所以我想我的问题是,在不影响面板内组件位置的情况下更改面板边框的最佳方法是什么?

下面是面板的鼠标侦听器:

panel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseEntered(MouseEvent e) {
            panel.setBorder(BorderFactory.createBevelBorder(1, Color.BLACK, Color.BLACK));
        }
        @Override
        public void mouseExited(MouseEvent e) {
            panel.setBorder(null);
        }
    });

JLabel是简单地使用边框布局添加的:

panel.setLayout(new BorderLayout());
JLabel label = new JLabel("testlabel");
panel.add(label,BorderLayout.PAGE_END);

您可以尝试在不使用斜角边框时使用 EmptyBorder。为其提供与斜面边框相同的宽度/高度。

我不会在布局或其经理上做很多混乱的事情,但这就是我会尝试的。

编辑

由于您似乎希望使用覆盖类型效果而不是边框,因此您可以创建自定义 JPanel 类并在 paintComponent(Graphics g) 方法中包含一些代码来绘制此覆盖。

类似于:

public class OverlayBorderJPanel extends JPanel
{
    boolean containsMouse = false; //set to true by mouseListener when contains
    BufferedImage overlay = //you would need to load an image border here, 
                            //rather than having a java created border
                            //You could have alpha so it is half see-through
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        if (containsMouse)
        {
            g.drawImage(//use 0,0 position with panel width/height)
        }
    }
}

我认为它可以处理这样的东西,但是您可能还需要在侦听器中调用面板的repaint()方法。

最新更新