简体   繁体   中英

how would I use a Font defined inside of a try{} block outside of the block in Java [resolved]

so, I'm working on a clock, and it needs a font (from an external file) to make it look like a 14-segment display instead of the Sans-Serif font it currently uses. However, the font doesn't work for the JLabel element I'm using, outside of the try block. how would I make the Font variable global?

try {
    Font dseg14 = Font.createFont(
        Font.TRUETYPE_FONT, new File("DSEG14ClassicMini-Regular.ttf")).deriveFont(12f);
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    ge.registerFont(dseg14);
} catch (IOException e) {
    e.printStackTrace();
} catch(FontFormatException e) {
    e.printStackTrace();
}

Main jFrame = new Main();
JLabel timeLabel = new JLabel();
DateTimeFormatter dateTimeFormatter = 
DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm.ss");
timeLable.setFont(dseg14);

(sorry, the code is quite messy)

resolved :D

解决

There's a number of ways you might deal with this situation, one would be to assign a reference of the Font to an instance field, one might be to have a "default" Font setup before you try and load your custom font, if the loading is successful, then you'd assign the custom font to this variable instead, for example...

Font font = // fallback font
try {
    dseg14 = Font.createFont(Font.TRUETYPE_FONT, new File("DSEG14ClassicMini-Regular.ttf")).deriveFont(12f);
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    ge.registerFont(dseg14);
    font = dseg14;
} catch (IOException e) {
    e.printStackTrace();
} catch (FontFormatException e) {
    e.printStackTrace();
}
//...

Another way might be to use Font(String, int, int) to load the font from the GraphicsEnvironment directly, for example...

在此处输入图像描述

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            try {
                Font font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/resources/DSEG14ClassicMini-Regular.ttf"));
                System.out.println(font.getName());
                System.out.println(font.getFamily());
                System.out.println(font.getFontName());
                GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font);
            } catch (FontFormatException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            // You could do this in the try-catch block above, but the
            // point is to demonstrate how it "might" be used after
            // the initialisation phase has completed
            Font font = new Font("DSEG14 Classic Mini", Font.PLAIN, 12);
            if (font != null) {
                setFont(font);
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            String text = "Hello World";
            FontMetrics fm = g2d.getFontMetrics();
            int x = (getWidth() - fm.stringWidth(text)) / 2;
            int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
            g2d.drawString(text, x, y);
            g2d.dispose();
        }

    }
}

BUT , you need to have a fallback workflow for what to do if you can't load the font. For example, I might have a initialisation phase, which must complete successfully before the rest of the application can run. This would allow you some "grace" in dealing with it and presenting a nice message to the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM