我在面板中繪制了許多形狀并且它可以工作,但是當我滾動面板或調整框架大小時,圖紙消失了。我查看了有關此主題的其他問題,但沒有找到解決問題的方法。截圖:編碼: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);
添加回答
舉報
0/150
提交
取消