当我只需单击按钮时,如何将 java 中的补充字符的字形打印到我的 JTextField 上

how to print a glyph of supplementary characters in java onto my JTextField when i just click the button

我有一个简单的程序,只需要在单击按钮时在 JTextField 上设置其 Unicode 值大于字符数据类型(补充字符)的字符。告诉我我真的受够了,我将如何做。这个问题已经花了我 4 天时间。

 //importing the packages
import java.awt.event.*;
import javax.swing.*;

import java.util.*;
import java.awt.*;

//My own custom class 
public class UnicodeTest implements ActionListener
{
JFrame jf;
JLabel jl;
JTextField jtf;
JButton jb;
UnicodeTest()
{
    jf=new JFrame();// making a frame
    jf.setLayout(null); //seting the layout null of this frame container
    jl=new JLabel("enter text"); //making the label 
    jtf=new JTextField();// making a textfied onto which a character will be shown
    jb=new JButton("enter");
//setting the bounds 
    jl.setBounds(50,50,100,50);
    jtf.setBounds(50,120,400,100);
    jb.setBounds(50, 230, 100, 100);
    jf.add(jl);jf.add(jtf);jf.add(jb);
    jf.setSize(400,400);
    jf.setVisible(true); //making frame visible
    jb.addActionListener(this); //  registering the listener object
}
public void actionPerformed(ActionEvent e) // event generated on the button click
{   try{

           int x=66560; //to print the character of this code point

           jtf.setText(""+(char)x);// i have to set the textfiled with a code point character which is supplementary in this case 

         }
     catch(Exception ee)// caughting the exception if arrived
        { ee.printStackTrace(); // it will trace the stack frame where exception arrive 
        }   
}
   // making the main method the starting point of our program
  public static void main(String[] args)
   {

    //creating and showing this application's GUI.
      new UnicodeTest();     
  }
}

由于您没有提供足够的信息来说明问题所在,我只能猜测其中一个或两个:

  1. 您没有使用可以显示该字符的字体。
  2. 您没有为文本字段提供正确的文本字符串表示形式。

设置可以显示字符的字体

并非所有字体都能显示所有字符。您必须找到一个(或多个)可以并设置 Swing 组件以使用该字体。您可用的字体取决于系统,因此适合您的字体可能不适用于其他人。您可以在部署应用程序时捆绑字体,以确保它适用于所有人。

为了在您的系统上找到可以显示您的角色的字体,我使用了

Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
for (Font f : fonts) {
    if (f.canDisplay(66560)) {
        System.out.println(f);
        textField.setFont(f.deriveFont(20f));
    }
}

输出(对我来说)是单一字体,所以我允许自己在循环中设置它:

java.awt.Font[family=Segoe UI Symbol,name=Segoe UI Symbol,style=plain,size=1]

正如 Andrew Thompson 对问题的评论中所指出的那样。

为文本字段提供正确的字符串表示形式

文本字段需要 UTF-16。 UTF-16 中的增补字符以两个代码单元编码(其中 2 个:\u12CD)。假设您从一个代码点开始,您可以将其转换为字符,然后从中创建一个字符串:

int x = 66560;
char[] chars = Character.toChars(x); // chars [0] is \uD801 and chars[1] is \uDC00
textField.setText(new String(chars)); // The string is "\uD801\uDC00"
// or just
textField.setText(new String(Character.toChars(x)));

正如 Andrew Thompson 在对此答案的评论中所指出的(之前我使用了 StringBuilder)。