为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

海绵宝宝撒 2022-04-28 15:50:01
我在面板中绘制了许多形状并且它可以工作,但是当我滚动面板或调整框架大小时,图纸消失了。我查看了有关此主题的其他问题,但没有找到解决问题的方法。截图:编码: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();        }    }}我该如何修复这个错误?
查看完整描述

1 回答

?
弑天下

TA贡献1818条经验 获得超8个赞

您正在破坏 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);


查看完整回答
反对 回复 2022-04-28
  • 1 回答
  • 0 关注
  • 125 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号