我有一个 JPanel,我使用通常的“paintComponent(Graphics g)”方法在其上绘制了许多自定义编写的 JComponent。我使用一个 JLayeredPane 来控制自定义组件的显示顺序,如下:
public Class MyPanel extends JPanel {
private JLayeredPane layeredPane = new JLayeredPane();
private JComponent component1;
private JComponent component2;
public MyPanel() {
super();
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
component1 = new CustomComponent1();
layeredPane.add (component1, new Integer(0));
component2 = new CustomComponent2();
layeredPane.add (component2, new Integer(1));
add (layeredPane);
}
public void resizePanel(Graphics g, int newWidth, int newHeight) {
component1.setBounds (f(x), f(y), f(newWidth), f(newHeight));
component2.setBounds (f(x), f(y), f(newWidth), f(newHeight));
}
public void paintComponent(Graphics g) {
if ((getWidth() != oldWidth) || (getHeight() != oldHeight)) {
oldWidth = getWidth();
oldHeight = getHeight();
resizePanel (g, getWidth(), getHeight());
}
super.paintComponent(g);
}
现在,我想将此面板导出为 JPEG 文件,但大小不同。当我使用以下代码时,它成功创建/导出了所需大小的 JPEG 文件,但它也将我的面板屏幕图像版本更新为新大小!哎呀!
public void export(File file, int width, int height)
throws IOException
{
BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = scaledImage.createGraphics();
resizePanel (g2, width, height);
super.paintComponent (g2);
try {
OutputStream out = new FileOutputStream(file);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(scaledImage);
out.close();
} catch (FileNotFoundException e) {
throw new IOException ("Unable to export chart to ("
+ file.getAbsolutePath() + "): " + e.getLocalizedMessage());
} finally {
g2.dispose();
}
}
如何“绘制”适合导出的图像,但实际上不会显示这个新图像?
谢谢!
好吧,我又回到这个问题了......
我正在绘制的场景包含一些文本,现在最终用户希望以“纵向”纵横比导出图形。由于我不是在新的维度上重新绘制场景,而只是缩放图像,这会导致文本被严重水平挤压。
反正围绕那个?