Search code examples
javagraphicsnotation

How could one draw a semibreve (whole note) in Java Swing?


I am creating a class to handle the creation of musical notation in my music training app, which is being built with Java Swing. As such, I am using the font Bravura for most of the symbols such as the treble clef and accidentals (using the Graphics drawString method with unicode characters).

However, I am unable to find a way to draw a semibreve, or a whole note, with this method; I get a rectangle instead of the desired character when I input the sequence "\uD834\uDD5D", which should correspond to a whole note, according to my research using fileformat.info.

My code for the JFrame is below:

public MusicalNotation() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);
    
    JTextArea semibreveTextArea = new JTextArea();
    semibreveTextArea.setBounds(50, 100, 200, 200);
    semibreveTextArea.setFont(new Font("Bravura", Font.PLAIN, 24));
    semibreveTextArea.setText("\uD834\uDD5D");
    contentPane.add(semibreveTextArea);
    semibreveTextArea.setBackground(getBackground());
    semibreveTextArea.setEditable(false);
}

However, the resulting window looks like the below:

enter image description here Are there any other fonts which have this functionality, or other ways to draw a semibreve?

Any help is much appreciated. Thank you in advance.


Solution

  • Are there any other fonts which have this functionality?. Yes there are (several) and and one of them is the font you are already using.

    The Bravura music font already contains the Semibreve and you shouldn't need to draw anything since Bravura is a font. All you need to do is provide the appropriate Unicode value for the notes, lines, and spacing you want and of course, the "\uD834\uDD5D" is valid for displaying the Semibreve note providing the Text component you are displaying the characters in has the Bravura font set to it (not all fonts support all of these Unicode music characters), for example:

    try {
        // Load the "Bravura.otf" font file.
        Font bravura = Font.createFont(Font.TRUETYPE_FONT, new File("Bravura.otf"));
        // Font Size - NEEDED! I believe default is 1. 
        // Set it to what you want but you may find 
        // size 12 too small.
        bravura = bravura.deriveFont(36f); 
        // Set the font to a JTextArea (or whatever).
        jTextArea1.setFont(bravura);
        // Display the Semibreve.
        jTextArea1.setText("\uD834\uDD5D");
    }
    catch (FontFormatException | IOException ex) {
        ex.printStackTrace();
    }
    

    You should see a Semibreve within the JTextAea.