滚动或调整主框架大小时,JPanel 中的绘图消失

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

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

截图:

http://img3.mukewang.com/626a47400001df6b02070233.jpghttp://img.mukewang.com/626a47460001334202030240.jpghttp://img4.mukewang.com/626a474b0001385302040232.jpg

编码:


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();

        }

    }

}

我该如何修复这个错误?


海绵宝宝撒
浏览 126回答 1
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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java