Java - 将JTextArea中的字符串转换为图像 [英] Java - Converting a string in JTextArea to an image

查看:96
本文介绍了Java - 将JTextArea中的字符串转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我希望输出与JTextArea完全相同。这是可能的吗?如果是的话,我该怎么看?

I would like the output to be exactly what is is the JTextArea. Is this possible and if so what should I look into?

推荐答案

assylias打败了我,但看到我如此接近我以为我会发布它

assylias beat me to it, but seen as I was so close I thought I'd post it anyway

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);

    }

}

来自此

到此

这篇关于Java - 将JTextArea中的字符串转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆