gpt4 book ai didi

Java - 将 JTextArea 中的字符串转换为图像

转载 作者:行者123 更新时间:2023-12-01 07:12:21 25 4
gpt4 key购买 nike

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

我希望输出与 JTextArea 完全相同。这可能吗?如果可能的话我应该研究什么?

最佳答案

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

}

}

从此

The Frmae

到此

The result

关于Java - 将 JTextArea 中的字符串转换为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11894064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com