【问题标题】:Swing: Paint over all other components and preserve eventsSwing:绘制所有其他组件并保留事件
【发布时间】:2013-01-09 19:12:33
【问题描述】:

我正在尝试做的事情:绘制一条垂直线和一条水平线,它们相互垂直并在鼠标指向的位置相交。一种光标跟踪器。

我的结构:JFrame -> CustomPanel -> 其他面板/组件等

CustomPanel 继承自 JPanel,它被设置为我的 JFrame 的 ContentPane。

我尝试使用 GlassPane,一切正常,但我想保留我的事件,而不是禁用它们。我仍然希望能够点击按钮等。

一个相关的问题是这个Painting over the top of components in Swing?。当我将鼠标移动到我的 CustomPanel 中的空白位置时,一切都按预期运行,但它仍然没有绘制在其他组件上。

在图像中它应该继续在按钮上绘画,但是当我进入它时它停止了,然后在我退出时恢复。

代码如下。

public class Painter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        JFrame frame = new JFrame();

        frame.setSize(600, 600);
        frame.setPreferredSize(new Dimension(600, 600));
        frame.setContentPane(new CustomPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

class CustomPanel extends JPanel {
    int x = 0;
    int y = 0;

    public CustomPanel() {

        addMouseListener(new AdapterImplementation(this));
        addMouseMotionListener(new AdapterImplementation(this));
        add(new JButton("TESTBTN"));
        setSize(new Dimension(600, 600));
        setPreferredSize(new Dimension(600, 600));
        setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.drawLine(0, y, getWidth(), y);
        g.drawLine(x, 0, x, getHeight());
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }
}

和我的适配器:

public class AdapterImplementation extends MouseAdapter {
    CustomPanel pane;

    public AdapterImplementation(CustomPanel pane) {
        this.pane = pane;
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        pane.setX(x);
        pane.setY(y);
        pane.repaint();
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        System.out.println("MOUSE MOVED");
        int x = e.getX();
        int y = e.getY();
        pane.setX(x);
        pane.setY(y);
        pane.repaint();
    }
}

【问题讨论】:

  • 只是一个猜测......您可能需要在自定义面板顶部有一个分层窗格,您将在其中绘制线条。

标签: java swing paint glasspane contentpane


【解决方案1】:

这里的问题是 MouseListeners 注册到您的 CustomPanel 但没有注册到 JButton 所以后者不处理来自侦听器的事件。

此外,正如您所见,使用 GlassPane 时,底层组件的事件将被阻止。

JLayeredPane 可以用作最顶层的容器,以使用您当前的侦听器捕获 MouseEvents

注意:在 Swing 中为自定义绘制覆盖 paintComponent 而不是 paint,并记得调用 super.paintComponent(g)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2013-10-08
    • 2013-01-28
    相关资源
    最近更新 更多