Unicode Character uncompatibility?

前端 未结 2 1037
你的背包
你的背包 2021-01-14 22:14

I have a problem with character encoding using swing on Java. I want to write this character:

\"\\u2699\"

That is a gear on a simple JButt

相关标签:
2条回答
  • 2021-01-14 22:38

    As mentioned by Andreas, use a Font that supports that character. But unless supplying a suitable font for the app., the Font API provides ways of discovering compatible fonts at run-time. It provides methods like:

    • Font.canDisplay(char)
    • Font.canDisplay(int)
    • Font.canDisplayUpTo(String)
    • and others.. see docs for details on all of them.

    In this example, we show the dozen fonts on this system that will display the gear character.

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    
    public class GearFonts {
    
        private JComponent ui = null;
        int codepoint = 9881;
        String gearSymbol = new String(Character.toChars(codepoint));
    
        GearFonts() {
            initUI();
        }
    
        public void initUI() {
            if (ui!=null) return;
    
            ui = new JPanel(new GridLayout(0,2,5,5));
            ui.setBorder(new EmptyBorder(4,4,4,4));
    
            Font[] fonts = GraphicsEnvironment.
                    getLocalGraphicsEnvironment().getAllFonts();
            for (Font font : fonts) {
                if (font.canDisplay(codepoint)) {
                    JButton button = new JButton(gearSymbol + " " + font.getName());
                    button.setFont(font.deriveFont(15f));
                    ui.add(button);
                }
            }
        }
    
        public JComponent getUI() {
            return ui;
        }
    
        public static void main(String[] args) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    GearFonts o = new GearFonts();
    
                    JFrame f = new JFrame(o.getClass().getSimpleName());
                    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    f.setLocationByPlatform(true);
    
                    f.setContentPane(o.getUI());
                    f.pack();
                    f.setMinimumSize(f.getSize());
    
                    f.setVisible(true);
                }
            };
            SwingUtilities.invokeLater(r);
        }
    }
    
    0 讨论(0)
  • 2021-01-14 22:41

    As @Andreas points out, the button needs to be set to use a font that supports this Unicode value. For sorting out compatibility issues such as this one, fileformat.info is a great resource. Here is the list of fonts known to support the Gear character. These include for example DejaVu Sans and Symbola.

    0 讨论(0)
提交回复
热议问题