【发布时间】:2015-09-19 05:46:39
【问题描述】:
this image 中的 JTextArea 的输出有一个奇怪的问题。我的程序要做的是通过 GUI 接受输入字符串,将其保存为图像,并将值 > 0 的每个像素设置为“”。这完全可以在控制台中找到,但是当它打印到 JTextArea 时,空格似乎是 '' 大小的一半。我知道这个问题不是我的代码的实际问题,而只是 JTextAreas 的一些内置问题。我将包含下面的代码,但我认为唯一相关的行就在最后:tA.setText(output);
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import javax.swing.*;
public class Project4 extends JPanel implements ActionListener {
public static Project4 p = new Project4();
public static JTextField input = new JTextField("Java 2D");
public static JTextArea tA = new JTextArea();
public static void main(String[] args) {
JFrame frame = new JFrame("Project 4");
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(p, BorderLayout.CENTER);
input.setColumns(40);
panel.add(input);
JButton print = new JButton("Print");
print.addActionListener(p);
panel.add(print);
panel.add(tA);
frame.add(panel);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
Font f = new Font("Times New Roman", Font.BOLD, 20);
FontRenderContext frc = new FontRenderContext(null, false, false);
GlyphVector gv = f.createGlyphVector(frc, input.getText());
Rectangle2D bounds = gv.getLogicalBounds();
TextLayout tL = new TextLayout(input.getText(), f, frc);
float ascent = tL.getAscent();
BufferedImage b = new BufferedImage((int) bounds.getWidth(),
(int) bounds.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2 = b.createGraphics();
g2.drawGlyphVector(gv, 0, ascent);
g2.setPaint(Color.BLACK);
g2.drawString(input.getText(), input.getAlignmentX(), input.getAlignmentY());
String output = "", line = "";
int spaceCount = 0;
Raster r = b.getRaster();
int[] i = new int[1];
for (int y = 0; y < (int) bounds.getHeight() - 1; y++) {
for (int x = 0; x < (int) bounds.getWidth() - 1; x++) {
r.getPixel(x, y, i);
int pixel = i[0];
if (pixel > 0) {
line += "*";
} else {
line += " ";
spaceCount++;
}
}
if (spaceCount != line.length())
output += line + "\n";
spaceCount = 0;
line = "";
}
System.out.print(output);
tA.setText(output);
}
}
** 感谢您的编辑,快蜗牛!
【问题讨论】:
-
尝试使用monospaced font,例如 Courier。
-
我不确定是不是字体,除非我可以更改 JTextArea 的字体。如果您看到,它在控制台中很好,但在 GUI 中很糟糕。我想它们可能是不同的字体,但这是我可以单独在 JTextArea 中设置的吗?
标签: java user-interface textarea