-1

我有一个简单的程序,只需要在单击按钮时在 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();     
  }
}
4

1 回答 1

4

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

  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 在对此答案的评论中所指出的那样(以前我使用过 a StringBuilder)。

在此处输入图像描述

于 2016-02-08T11:39:22.847 回答