我在 JTextPane/JTextField 中发现了一个奇怪的错误(或者在它们下面的字体渲染中的某个地方)。我想知道是否有其他人遇到过同样的情况,并且可能对此有解决方案。
我试图在 JTextPane 中显示一些“特殊”或稀有字符,并且一旦我更改 JTextField 的字体(与 JTextPane 完全无关!),JTextPane “分解”,不再显示这些人物。
这应该更好地解释我的意思:
public class Scrap {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setLayout(new BorderLayout());
JTextField field = new JTextField();
// Uncomment this line... and the JTextPane nor the JTextField
// no longer display the characters
// field.setFont(new Font("Arial", Font.PLAIN, 14));
frame.add(field, BorderLayout.SOUTH);
JTextPane textPane = new JTextPane();
textPane.setFont(new Font("Arial", Font.PLAIN, 14));
JScrollPane scroll = new JScrollPane(textPane);
frame.add(scroll, BorderLayout.CENTER);
StyledDocument doc = (StyledDocument) textPane.getDocument();
try {
String str = "◕ ◡◡ ◕";
doc.insertString(doc.getLength(), str, null);
} catch (BadLocationException e) {
e.printStackTrace();
}
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
编辑:这是一个更好的问题示例。它似乎与字体的大小有关。移动 Slider,您会注意到 14 的大小不会呈现字形,而 14 恰好是 JTextField 的 Font 的大小。
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.*;
import java.awt.*;
public class Scrap {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 200);
frame.setLayout(new BorderLayout());
final JTextField field = new JTextField(10);
final JTextPane textPane = new JTextPane();
StyledDocument doc = (StyledDocument) textPane.getDocument();
JPanel panel = new JPanel();
frame.add(panel, BorderLayout.SOUTH);
// Set the Font of the JTextField, and the JTextPane
// no longer displays the text of that size correctly...
int changeMe = 14;
field.setFont(new Font("Tahoma", Font.PLAIN, changeMe));
// If we change the Font Family, the problem goes away...
// field.setFont(new Font("Dialog", Font.PLAIN, 14));
panel.add(field);
final JLabel label = new JLabel();
final JSlider slider = new JSlider(6, 32);
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
textPane.setFont(new Font("Tahoma", Font.PLAIN, slider.getValue()));
textPane.selectAll();
SimpleAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setFontSize(attr, slider.getValue());
textPane.setCharacterAttributes(attr, true);
label.setText("" + slider.getValue());
}
});
slider.setValue(14);
panel.add(slider);
panel.add(label);
JScrollPane scroll = new JScrollPane(textPane);
frame.add(scroll, BorderLayout.CENTER);
Style s = doc.addStyle("test", null);
try {
String str = "◕ ◡◡ ◕";
doc.insertString(doc.getLength(), str, doc.getStyle("test"));
} catch (BadLocationException e) {
e.printStackTrace();
}
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}