0

我有一个字符串显示在我的程序中,但我想知道如何将字符串的输出转换为与原始字符串相同的图像。不知道这是否可以做到。

我希望输出与 JTextArea 完全相同。这可能吗?如果可以,我应该调查什么?

4

2 回答 2

5

assylias 打败了我,但看到我离得太近了,我想我还是会发布它

public class TestFrame extends JFrame {

    private JTextArea text;

    public TestFrame() {

        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setTitle("Text");

        setLayout(new BorderLayout());
        text = new JTextArea();
        add(new JScrollPane(text));

        JButton btnPrint = new JButton("Print");
        add(btnPrint, BorderLayout.SOUTH);

        btnPrint.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                BufferedImage img = new BufferedImage(text.getWidth(), text.getHeight(), BufferedImage.TYPE_INT_RGB);
                Graphics2D g2d = img.createGraphics();
                text.printAll(g2d);
                g2d.dispose();

                try {
                    ImageIO.write(img, "png", new File("StringToGraphics.png"));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

            }
        });

        text.setWrapStyleWord(true);
        text.setColumns(15);
        text.setLineWrap(true);
        text.setText("I have a string which is displayed in my program, but I'm wondering how I would convert the output of the string into an image identical to the original string. No idea if this can be done.\n\nI would like the output to be exactly what is is the JTextArea. Is this possible and if so what should I look into?");

        setSize(200, 300);

        setLocationRelativeTo(null);
        setVisible(true);

    }

}

由此

框架

对此

结果

于 2012-08-10T01:34:00.970 回答
3

您可以使用ScreenImagecreateImage使用该方法从组件创建图像。总而言之,这是它在幕后所做的(使用 JLabel):

public static void main(String args[]) throws AWTException, IOException {

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame frame = new JFrame("test");
            JLabel text = new JLabel("text");
            frame.add(text);
            frame.setPreferredSize(new Dimension(100, 100));
            frame.pack();
            frame.setVisible(true);

            BufferedImage img = getImage(text);
            try {
                ImageIO.write(img, "png", new File("C:/temp/img.png"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });
}

private static BufferedImage getImage(JComponent c) {
    Rectangle region = c.getBounds();
    BufferedImage image = new BufferedImage(region.width, region.height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = image.createGraphics();
    g2d.translate(-region.x, -region.y);
    g2d.setColor(c.getBackground() );
    g2d.fillRect(region.x, region.y, region.width, region.height);
    c.paint(g2d);
    g2d.dispose();
    return image;
}
于 2012-08-10T01:25:10.293 回答