【问题标题】:Drawing in JPanel disappears when scrolling or ressizing the main frame滚动或调整主框架大小时,JPanel 中的绘图消失
【发布时间】:2019-01-11 00:20:27
【问题描述】:

我在面板中绘制了许多形状并且它可以工作,但是当我滚动面板或调整框架大小时,绘图消失了

我查看了有关此主题的其他问题,但没有找到解决问题的方法。

截图:

代码:

public class ZoomPane {

    public static void main(String[] args) {
        new ZoomPane();
    }

    public ZoomPane() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                .  . .
            }
        });
    }

    public class TestPane extends JPanel {

        private float scale = 1;

        public TestPane() {
            addMouseWheelListener(new MouseAdapter() {

                @Override
                public void mouseWheelMoved(MouseWheelEvent e) {
                    double delta = 0.05f * e.getPreciseWheelRotation();
                    scale += delta;
                    revalidate();
                    repaint();
                }

            });
        }

        @Override
        public Dimension getPreferredSize() {
            Dimension size = new Dimension(200, 200);
            size.width = Math.round(size.width * scale);
            size.height = Math.round(size.height * scale);
            return size;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            AffineTransform at = new AffineTransform();
            at.scale(scale, scale);
            g2d.setTransform(at);

            g2d.setColor(Color.RED);


            gr.draw(new Line2D.Double((int)this.getWidth() / 2, 0, (int)this.getWidth() / 2, this.getHeight())); 
            gr.draw(new Line2D.Double(0, (int)this.getHeight() / 2, this.getWidth(), (int)this.getHeight() / 2));


            g2d.dispose();
        }
    }
}

如何修复此错误?

【问题讨论】:

  • 请包含重现您的错误所需的所有代码
  • 滚动和调整大小时,JPanel 必须重绘。如果您的 paintComponent 方法将绘制调用的绘制内容从绘制调用更改为绘制调用(换句话说,有动画),那么您将遇到无法完全按照您的预期绘制的问题。
  • @elbraulio,这就是所有代码。哪里有注释(//绘图)这样的代码:gr.draw(new Line2D.Double((int)this.getWidth() / 2, 0, (int)this.getWidth() / 2, this.getHeight())); gr.draw(new Line2D.Double(0, (int)this.getHeight() / 2, this.getWidth(), (int)this.getHeight() / 2));

标签: java


【解决方案1】:

您正在破坏 Swing 实施的 Graphics2D 变换。 JScrollPane 依赖它。

您需要追加而不是替换转换。替换这个:

AffineTransform at = new AffineTransform();
at.scale(scale, scale);
g2d.setTransform(at);

用这个:

AffineTransform at = new AffineTransform();
at.scale(scale, scale);
g2d.transform(at);

setTransform 替换变换; transform 方法附加到它。

更简洁的解决方案是将所有三行替换为:

g2d.scale(scale, scale);

【讨论】:

    猜你喜欢
    • 2015-04-24
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 2012-06-26
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多