Считать Unicode из компонента Swing и отобразить его в компоненте Swing не удалось - PullRequest
0 голосов
/ 16 сентября 2011

Я пытаюсь отобразить строку Unicode в таблице, как указано в следующей программе.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author dell
 */
public class UnicodeExample extends javax.swing.JFrame {

    /** Creates new form UnicodeExample */
    public UnicodeExample() {
        initComponents();
        setTitle("Unicode Example");
        setSize(400, 400);
        setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel1.setText("Enter :");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(24, 50, 70, 20);

        jTextField1.setText("\\u00a5");
        getContentPane().add(jTextField1);
        jTextField1.setBounds(110, 50, 220, 20);

        jButton1.setText("Display Entered UniCode");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(120, 110, 160, 23);
        getContentPane().add(jLabel2);
        jLabel2.setBounds(120, 170, 150, 40);

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here
        String uniCode = jTextField1.getText();

        jLabel2.setText(uniCode);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new UnicodeExample().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}

Но символы Unicode не отображаются.Это происходит только тогда, когда я получаю значение из внешнего источника в качестве параметра и устанавливаю это значение в элемент управления Swing.Но нет проблем, если я жестко закодирую строку вроде String unicode="\u00a5"

Есть ли какое-нибудь решение этой проблемы?

1 Ответ

1 голос
/ 16 сентября 2011

Жесткое кодирование работает, потому что \u00a5 рассматривается как один единственный символ Юникода в этом случае.

Однако при получении от JTextField вы получаете STRING "\u00a5", что эквивалентно "\\u00a5" если у вас жесткий код.

Для большей ясности попробуйте

char c = '\u00a5';

System.out.println(c);

Редактировать:

Если вы вставляете только юникодные представления в поле ввода, этот небольшой код может помочь:

String uniCode = jTextField1.getText();

uniCode = uniCode.substring(2);        
char c = (char) Integer.parseInt(uniCode, 16);                

jLabel2.setText(c + "");

Сделайте это в методе actionPerformed.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...