我在面板中绘制了许多形状并且它可以工作,但是当我滚动面板或调整框架大小时,绘图会消失。
我查看了有关此主题的其他问题,但没有找到该问题的解决方案。
截图:
代码:
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();
}
}
}
如何修复此错误?
最佳答案
您正在破坏 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);
关于java - 滚动或调整主框架大小时,JPanel 中的绘图消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54131279/