2

私のプログラムでは、さまざまな JComponents (通常は JPanel) を頻繁に印刷する必要があり、それらをフルページにしたいと考えています。私が今それを行う方法は、次のコードを使用することです。

g2d.scale(pf.getImageableWidth()/componentToPrint.getWidth(), pf.getImageableHeight()/componentToPrint.getHeight());

しかし、これは私が印刷しようとしているものは何でも伸びたり変形したりすることがよくあります.

componentToPrint.setSize(pf.ImageableWidth(), pf.ImageableHeight);

または、コンポーネントを新しい JFrame に追加してから、フレーム サイズを設定するとします (問題は、コンポーネントが一度に 2 つの場所に存在できないことです)。簡単にリセットできるものである限り、サイズ変更によって残りの GUI が見栄えが悪くなっても気にしません。

これを行う方法はありますか?

4

4 に答える 4

2

あなたが探している解決策は、目的のコンテンツを含む新しい JPanel を構築し、代わりにコピーを印刷することだと思います。CellRendererPane を使用すると、探しているように聞こえる正確なサイズ変更動作を取得できます。

JComponents が十分に適切に作成されている場合、新しいものを新しく作成し、そのモデルを元のものと同じに設定することは問題になりません。

CellRendererPane cellRendererPane = new CellRendererPane();
// It's important to add the cell renderer pane to something
// you can use the same one for all of your exporting if you like and just
// add it to your main frame's content pane - it won't show up anywhere.
add(cellRendererPane);

JPanel printPanel = createCopy(panel);
cellRendererPane.paintComponent(g, printPanel, null, 0, 0, exportDim.width, exportDim.height, true);

これが完全な動作例です。createPanel() メソッドは、レンダリングしたいコンポーネントを作成する必要があります。実際の例では、使い捨てコンポーネント用に新しいモデルを再作成するのではなく、必ず同じモデルを使用する必要があります。

public class SCCE {

    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        final JFrame f = new JFrame("SCCE");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(SCCE.createPanel());

        final CellRendererPane backgroundRenderer = new CellRendererPane();

        // Add the renderer somewhere where it won't be seen
        f.getContentPane().add(backgroundRenderer, BorderLayout.NORTH);
        f.getContentPane().add(createSaveButton(backgroundRenderer), BorderLayout.SOUTH);

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    // Create your custom component from whatever model here..
    private static final Component createPanel() {
        DefaultListModel model = new DefaultListModel();
        for (int i = 0; i < 10; i++) {
            model.addElement("Item number " + i);
        }
        return new JList(model);
    }

    private static JButton createSaveButton(final CellRendererPane backgroundRenderer) {
        return new JButton(new AbstractAction("Save image to file") {
            @Override
            public void actionPerformed(ActionEvent e) {
                Dimension d = new Dimension(400, 300);

                BufferedImage img = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB);
                Graphics2D g = img.createGraphics();
                backgroundRenderer.paintComponent(g, createPanel(), null, 0, 0, d.width, d.height, true);
                g.dispose();

                try {
                    File output = new File("test.png");
                    System.err.println("Saved to " + output.getAbsolutePath());
                    ImageIO.write(img, "png", output);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

}
于 2009-11-05T20:15:47.467 に答える
1

あなたが直面している問題は、スケール操作とは何の関係もないと思います。間違っているのはあなたの論理です。ほとんどの場合、Imageable のスケールとコンポーネントのスケールは同じではないため、x と y のスケールは異なります。これが、スケール操作後にコンポーネントが歪む理由です。次のようなことをしなければなりません:

double factorX = pf.getImageableWidth() / component.getWidth();
double factorY = pf.getImageableHeight() / component.getHeight();
double factor = Math.min( factorX, factorY );
g2.scale(factor,factor);

その後、新しいサイズに応じて画像を適切な座標に変換できます。それが役に立てば幸い...

于 2009-08-03T13:48:40.913 に答える
1

paintComponent()描画コードを、実装のメソッドから、任意の幅/高さJPanelの任意のオブジェクトに描画できるそのパネルの public/package protected メソッドにリファクタリングしますGraphics(おそらく、描画コードは十分に一般的です)。

この例には、いくつかの描画ロジック (大きな X、パネルのサイズ) を持つパネルを含むフレームがあります。この例の主な方法は、画像のサイズがパネルのサイズと異なる場合でも、画像を取得してファイルに書き込む方法を示しています。


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MockFrame extends JFrame {

    // throws Exception, as just an example (not really advised to do this)
    public static void main(String[] args) throws Exception {
        MockFrame frame = new MockFrame();
        frame.setVisible(true);

        // different sizes from the frame
        int WIDTH = 500;
        int HEIGHT = 500;

        BufferedImage b = new BufferedImage(WIDTH, HEIGHT,
            BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2d = (Graphics2D) b.getGraphics();

        // should set some background, as the panel's background
        // is dealt with by super.paintComponent()
        g2d.setBackground(Color.white);

        frame.getPanel().drawingLogic(b.getGraphics(), WIDTH, HEIGHT);

        ImageIO.write(b, "png", new File("test.png"));

    }

    private MockPanel panel;

    public MockFrame() {
        this.setSize(200, 200);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        panel = new MockPanel();
        getContentPane().add(panel);
    }

    public MockPanel getPanel() {
        return panel;
    }

    private class MockPanel extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        drawingLogic(g, getWidth(), getHeight());
    }

    public void drawingLogic(Graphics g, int width, int height) {
        g.setColor(Color.black);

        g.drawLine(0, 0, width, height);
        g.drawLine(0, height, width, 0);
    }
    }
}

これにより、GUI の外部にあるオブジェクトをその描画アルゴリズムにフックできます。私が見た欠点の 1 つは、パネルを印刷したいオブジェクトとパネルの実際の実装との間に依存関係を作成することです。しかし、その場でパネルのサイズを変更するよりはまだましです (私はそれを試しましたが、いくつかの問題があるようです - 変更が反映されるまでには時間がかかると思いますsetSize().

編集:

コメントに応えて、上記のコード スニペットの修正版を提供しました。これはおそらく最適な方法ではなく、ユーザー フレンドリーでもありません (したがって、エンド ユーザー アプリケーションでは使用しません) が、レイアウト マネージャーの規則に従ってフレーム内のすべてのサイズを変更します。


/* This code snippet describes a way to resize a frame for printing at 
 * a custom size and then resize it back.
 * 
 * Copyright (C)   
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see .
 */

import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class MockFrame extends JFrame {

    // throws Exception, as just an example (not really advised to do this)
    public static void main(String[] args) throws Exception {
        final MockFrame frame = new MockFrame();
        frame.setVisible(true);

        // different sizes from the frame
        final int WIDTH = 500;
        final int HEIGHT = 700;

        final BufferedImage b = new BufferedImage(WIDTH, HEIGHT,
                BufferedImage.TYPE_INT_ARGB);

        final Graphics2D g2d = (Graphics2D) b.getGraphics();

        final int previousWidth = frame.getWidth();
        final int previousHeight = frame.getHeight();

        frame.setSize(WIDTH, HEIGHT);
        frame.repaint();

        JOptionPane.showMessageDialog(null,
                "Press OK when the window has finished resizing");

        frame.print(g2d);
        frame.setSize(previousWidth, previousHeight);
        ImageIO.write(b, "png", new File("test.png"));

    }

    public MockFrame() {
        this.setSize(200, 200);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        boolean shouldFill = true;
        boolean shouldWeightX = true;

        Container pane = getContentPane();

        // code from
        // http://java.sun.com/docs/books/tutorial/uiswing/layout/gridbag.html
        // just to add some components in the frame... :)
        // left out in here for brevity

    }

}

コードは基本的にフレームのサイズを変更し、ユーザーに確認メッセージを表示して、再描画が完了するまでスレッドをブロックできるようにします ( で実行できますがThread.sleep()、メッセージを使用するとより透過的になります)。次に、フレームを印刷し、サイズを変更して元の形状に戻します。少しハックですが、動作します。

-- Flaviu Cipcigan

于 2009-08-03T13:52:49.023 に答える
0

あなたはあなた自身の質問に答えたと思います。各コンポーネントにはメソッドがあります:

setSize(int width, int height);
于 2009-08-03T09:43:16.207 に答える