我正在做一个项目,使 JApplet 的内容自动缩放到 html 中指定的大小。我意识到这是布局管理器的用途,但是由于不允许我重写整个小程序结构,所以我决定尝试覆盖绘画并简单地将图形对象的 AffineTransform 设置为适当缩放的版本,然后在顶部容器中捕获鼠标事件,并使用适当的缩放变换将它们缩小。我现在卡在绘图部分了。当在 Web 浏览器中查看时,它会正确渲染缩放版本一次,然后图像会缩小回其原始大小。此外,JApplet 中的 paint 方法似乎只被调用过一次。这是我的代码的裁剪版本,着重于该问题。任何帮助,将不胜感激。提前致谢。
import javax.swing.JApplet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
public class Test extends JApplet
{
public static final int ORIGINAL_APPLET_WIDTH = 1024;
public static final int ORIGINAL_APPLET_HEIGHT = 800;
private AffineTransform scalingTransform;
private AffineTransform inverseScalingTransform;
@Override
public void init()
{
double xFactor = ((double)(this.getWidth()))/((double)(Test.ORIGINAL_APPLET_WIDTH));
double yFactor = ((double)(this.getHeight()))/((double)(Test.ORIGINAL_APPLET_HEIGHT));
this.scalingTransform = new AffineTransform();
this.inverseScalingTransform = new AffineTransform();
this.scalingTransform.scale(xFactor,yFactor);
this.inverseScalingTransform.scale(1D/xFactor,1D/yFactor);
}
@Override
public void paint(Graphics g)
{
((Graphics2D)g).setTransform(Test.this.scalingTransform);
super.paint(g);
}
}
最佳答案
经过大量研究,我发现问题在于 JApplet 的绘制方法并不经常被调用。相反,内容 Pane 有自己的绘图表面,所以我只需更换内容 Pane 即可上传。这是我做的方式:
@Override
public void init()
{
double xFactor = ((double)(this.getWidth()))/((double)(qt.ORIGINAL_APPLET_WIDTH));
double yFactor = ((double)(this.getHeight()))/((double)(qt.ORIGINAL_APPLET_HEIGHT));
this.scalingTransform = new AffineTransform();
this.inverseScalingTransform = new AffineTransform();
this.scalingTransform.scale(xFactor,yFactor);
this.inverseScalingTransform.scale(1D/xFactor,1D/yFactor);
JPanel drawScale = new JPanel()
{
@Override
public void paint(Graphics g)
{
((Graphics2D)g).setTransform(Test.this.scalingTransform);
super.paint(g);
}
@Override
public void paintAll(Graphics g)
{
((Graphics2D)g).setTransform(Test.this.scalingTransform);
super.paintAll(g);
}
@Override
public void paintComponents(Graphics g)
{
((Graphics2D)g).setTransform(Test.this.scalingTransform);
super.paintComponents(g);
}
@Override
public void paintComponent(Graphics g)
{
((Graphics2D)g).setTransform(Test.this.scalingTransform);
super.paintComponents(g);
}
};
Container oldPane = this.getContentPane();
drawScale.setLayout(oldPane.getLayout());
this.setContentPane(drawScale);
}
这些绘画方法当然是小程序中的方法的补充。
关于java - 覆盖 JApplet 中的绘制方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4669715/