通常の「paintComponent(Graphics g)」メソッドを使用して多数のカスタム作成 JComponents を描画する JPanel があります。次のように、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();
}
}
エクスポートに適した画像を「描画」できますが、実際にはこの新しい画像が表示されませんか?
ありがとう!
さて、またこの問題に戻ってきました……。
私が描いているシーンにはいくつかのテキストが含まれており、エンド ユーザーはグラフを「ポートレート」アスペクト比でエクスポートすることを望んでいます。シーンを新しい次元で再描画するのではなく、画像をスケーリングするだけなので、テキストが水平方向に大きく押しつぶされます。
とにかくそのあたり?