我使用JTextArea
打开了一个文件,并将文本替换为某些Unicode字符,但这些字符是可读的。问题是如何设置那些字符不可读,复制和粘贴以及何时选择符号未出现的文字?
String previous=textArea.getText();
if(button.isSelected()){
previous=previous.replaceAll(" ","\u00b7");
previous=previous.replaceAll("\t","\u00BB\t");
textArea.setText(previous.replaceAll("\n", "\u00B6\n"));
}
答案 0 :(得分:5)
使用Font.canDisplayUpTo(String)
检查文本区域的字体是否可以显示给定String
中的所有字符。
以下是一个使用示例:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class UnicodeCharacterTest {
private JComponent ui = null;
String s = new String(
new String(Character.toChars(182)) + " "
+ new String(Character.toChars(183)) + " "
+ new String(Character.toChars(186)));
UnicodeCharacterTest() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new GridLayout(0, 2));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
GraphicsEnvironment ge
= GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = ge.getAllFonts();
for (Font font : fonts) {
if (font.canDisplayUpTo(s)<0) {
ui.add(new JLabel(font.getName()));
JLabel output = new JLabel(s);
output.setFont(font.deriveFont(24f));
ui.add(output);
}
}
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
UnicodeCharacterTest o = new UnicodeCharacterTest();
JFrame f = new JFrame("Font/Unicode test");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(new JScrollPane(
o.getUI(),
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
f.pack();
f.setSize(new Dimension(f.getSize().width,200));
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}