Set font swing java

Java Swing 2D. Шрифты

Помимо конструкторов класс Font имеет дополнительные методы для создания новых шрифтов:

  • decode(String str) — статический метод создающий шрифт по строке описания, например вызов с аргументом «Arial-BOLD-18» аналогично конструктору new Font(«Arial», Font.BOLD, 18). Строка может принимать один из следующий форматов:
    • имя_шрифта-стиль-размер
    • имя_шрифта-стиль
    • имя_шрифта-размер
    • имя_шрифта стиль размер
    • имя_шрифта стиль
    • имя_шрифта размер
    • имя_шрифта

    стиль, размер и аффинное преобразование

    • getItalicAngle() — угол наклона;
    • getSize() — размер точки данного шрифта как число типа int;
    • getSize2D() — размер точки данного шрифта как число типа float;
    • getStyle() — текущий стиль шрифта;
    • getTransform() — текущее преобразование связанное с данным шрифтом;
    • isBold() — имеет ли шрифт стиль BOLD;
    • isItalic() — имеет ли шрифт стиль ITALIC;
    • isPlain() — имеет ли шрифт стиль PLAIN;
    • isTransformed() — применено ли аффинное преобразование к данному шрифту.

    атрибуты шрифта

    • getAttributes() — получить атрибуты шрифта в виде объекта типа Map;
    • getAvailableAttributes() — получить массив ключей для всех атрибутов поддерживаемых данным шрифтом;
    • hasLayoutAttributes() — содержит ли шрифт атрибуты требующих дополнительной обработки расположения.

    метрические линии

    Для вывода символов используются ряд линий вдоль которых и распологаются символы. Например, базовая линии определяет месторасположения символов не имеющих подстрочной части как символ o. Информация о них содержится в абстрактном классе LineMetrics. Один и тот же шрифт может иметь различные метрики для различных диапазонов символов. Для получения значений этих линий для указанного текста в классе Font предусмотрено четыре метода, различающихся способом задания текста:

    • getLineMetrics(char[] chars, int beginIndex, int limit, FontRenderContext frc);
    • getLineMetrics(CharacterIterator ci, int beginIndex, int limit, FontRenderContext frc);
    • getLineMetrics(String str, FontRenderContext frc);
    • getLineMetrics(String str, int beginIndex, int limit, FontRenderContext frc);
    • getBaselineFor(char c) — базовая линия для отображения указанного символа;
    • hasUniformLineMetrics() — имеет ли шрифт однородные метрические линии. Разнородность может появиться если логический шрифт для отображения символов использует несколько различных физических шрифтов.

    Ниже приведены методы класса LineMetrics:

    • getAscent() — верхняя граница до которой доходит надстрочная часть образа символа
      (например, в d и t), обычно определяет высоту заглавной буквы;
    • getDescent() — нижняя граница до которой доходит подстрочная часть образа символа
      (например, в q и g);
    • getHeight() — высота текста;
    • getLeading() — межстрочное расстояние — рекомендуемое расстояние от нижней границы
      одной строки текста до верхней границы следующей;
    • getNumChars() — число символов в тексте для которого были вычислены метрики;
    • getBaselineIndex() — индекс базовой линии текста:
      • ROMAN_BASELINE — базовая линия, используемая в большинстве романских алфавитов;
      • CENTER_BASELINE — базовая линия, используемая в алфавитах с иероглифами как японский;
      • HANGING_BASELINE — базовая линия, используемая в алфавитах сходных с деванагари;

      В следующем примере выводится текст и некоторые соответствующие ему линии.

      public class MyComponent extends JComponent < private static final long serialVersionUID = 1L; private Font f = new Font("TimesRoman", Font.PLAIN, 42); private String str = "replica: Hello world"; public MyComponent() < >@Override public void paint(Graphics g) < float x = 10, y = 60; Graphics2D g2 = (Graphics2D) g; // очищаем фон Dimension d = getSize(null); g2.setBackground(Color.white); g2.clearRect(0, 0, d.width, d.height); // получаем контекст отображения шрифта FontRenderContext frc = g2.getFontRenderContext(); // получаем метрики шрифта LineMetrics lm = f.getLineMetrics(str, frc); // устанавливаем шрифт g2.setFont(f); // вывод базовой линия шрифта double width = f.getStringBounds(str, frc).getWidth(); g2.setColor(Color.cyan); g2.draw(new Line2D.Double(x, y, x + width, y)); // вывод верхней границы g2.setColor(Color.red); g2.draw(new Line2D.Double(x, y - lm.getAscent(), x + width, y - lm.getAscent())); // вывод нижней границы g2.setColor(Color.green); g2.draw(new Line2D.Double(x, y + lm.getDescent(), x + width, y + lm.getDescent())); // вывод межстрочного расстояния g2.setColor(Color.blue ); g2.draw(new Line2D.Double(x, y + lm.getDescent() + lm.getLeading(), x + width, y + lm.getDescent() + lm.getLeading())); g2.setColor(Color.black ); g2.drawString(str, x, y); >>

      глифы

      Информацию о глифах можно получить следующими методами класса Font:

      • canDisplay(char c) — есть ли в шрифте образ для указанного символа;
      • canDisplay(int codePoint) — есть ли в шрифте образ для указанного символа;
      • canDisplayUpTo(char[] txt, int start, int limit) — может ли шрифт отобразить символы в указанной части строки. Возвращаемое значение >0 указывает индекс первого не отображаемого символа, -1 если все символы могут быть отображены;
      • canDisplayUpTo(CharacterIterator it, int start, int limit) — аналогично предыдущему для диапазона символов;
      • canDisplayUpTo(String str) — аналогично предыдущему для символов строки;
      • getStringBounds(char[] chars, int beginIndex, int limit, FontRenderContext frc) — логические границы для указанного текста в указанном контексте отображения шрифта. Как и в canDisplayUpTo текст можно указать различными способами;
      • getNumGlyphs() — число глифов в данном шрифте;
      • getMissingGlyphCode() — код глифа, используемого по умолчанию, когда нет нужного глифа;
      • createGlyphVector(FontRenderContext frc, char[] chars) — получить глифы указанных символов;
      • createGlyphVector(FontRenderContext frc, CharacterIterator ci) — получить глифы указанных символов;
      • createGlyphVector(FontRenderContext frc, String str) — получить глифы указанных символов;
      • layoutGlyphVector(FontRenderContext frc, char[] text, int start, int limit, int flags) — получить глифы, выполняя повозможности полное расположение текста. Метод нужен для языков со сложным алфавитом как арабский и хинди.

      Источник

      Adding fonts to Swing application and include in package

      I need to use custom fonts (ttf) in my Java Swing application. How do I add them to my package and use them? Mean while, I just install them in windows and then I use them, but I don’t wish that the usage of the application will be so complicated, it`s not very convenient to tell the user to install fonts before using my application.

      @DanM If you opened a bounty on purpose because you are not satisfied with the current answers, you should clarify why it does not answer your question and/or what additional information you need.

      3 Answers 3

      You could load them via an InputStream :

      InputStream is = MyClass.class.getResourceAsStream("TestFont.ttf"); Font font = Font.createFont(Font.TRUETYPE_FONT, is); 

      This loaded font has no predefined font settings so to use, you would have to do:

      Font sizedFont = font.deriveFont(12f); myLabel.setFont(sizedFont); 

      Or if it is in a package, you can access it by the full package name. eg: i have ttf file foo.ttf in package foo.bar.master.cork, I would access it through getResourceAsStream(«/foo/bar/master/cork/foo.ttf») . What this means is: put a forward slash at the start, replace every dot with a forward slash (except in the filename.), and a forward slash at the end of the path but before the file.

      As Reimeus said, you can use an InputStream . You can also use a File :

      File font_file = new File("TestFont.ttf"); Font font = Font.createFont(Font.TRUETYPE_FONT, font_file); 

      In both cases you would put your font files in either the root directory of your project or some sub-directory. The root directory should probably be the directory your program is run from. For example, if you have a directory structure like:

      My_Program | |-Fonts | |-TestFont.ttf |-bin |-prog.class 

      you would run your program with from the My_Program directory with java bin/prog . Then in your code the file path and name to pass to either the InputStream or File would be «Fonts/TestFont.ttf» .

      Источник

      Using setFont in Java

      Using setFont in Java

      1. Using setFont() to Set a New Font in JFrame
      2. Using setFont() and getFont().deriveFont() to Set a Style in the Existing Font
      3. Using setFont() and Font.createFont() to Set a Custom Font

      In this article, we will learn how we can use the setFont() method inherited from java.awt.Container in the javax.swing.JFrame class. As the name suggests, this function sets the font to the components of JFrame .

      Using setFont() to Set a New Font in JFrame

      In this example, we set a new font to a JFrame component.

      First, we create a JFrame object and two labels of the JLabel type. We initialize the labels with their text.

      Now we create a Font object called myFont1 , and in the constructor, we pass three arguments, first is the font that we want to set, second is the font style which can be called using Font class, and the last argument is the font size that is an int type value.

      We create another Font object, myFont2 , and set a pass a different font value to it. We call the setFont() function using the JLabel objects and pass the Font objects to them.

      After that, we set the position and size of the components using the setBounds() function and add them to the JFrame using add() . At last, we set the size and visibility of the JFrame .

      import javax.swing.*; import java.awt.*;  public class Main    public static void main(String[] args)   JFrame jFrame = new JFrame("Set Font Example");  JLabel jLabel1, jLabel2;   jLabel1 = new JLabel("Label with Serif Font");  jLabel2 = new JLabel("Label with Arial Font");   Font myFont1 = new Font("Serif", Font.BOLD, 12);  jLabel1.setFont(myFont1);   Font myFont2 = new Font("Arial", Font.BOLD, 12);  jLabel2.setFont(myFont2);   jLabel1.setBounds(80, 100, 120, 30);  jLabel2.setBounds(80, 80, 120, 30);   jFrame.add(jLabel1);  jFrame.add(jLabel2);  jFrame.setSize(300, 300);   jFrame.setLayout(null);  jFrame.setVisible(true);   > > 

      Java setFont

      Using setFont() and getFont().deriveFont() to Set a Style in the Existing Font

      In the previous example, we saw how setFont() can be used to set a new font, but we can use this method also to set a new style to the existing font of the JFrame component.

      To achieve this, we first get the component’s font using the component.getFont() and call the deriveFont() function that accepts the style that we want to apply. We pass Font.ITALIC to make the font on the JLabel Italic.

      import javax.swing.*; import java.awt.*;  public class Main    public static void main(String[] args)   JFrame f = new JFrame("Set Font Example");  JLabel jLabel1;   jLabel1 = new JLabel("Label with Italic Style");   jLabel1.setFont(jLabel1.getFont().deriveFont(Font.ITALIC));  jLabel1.setBounds(80, 100, 120, 30);   f.add(jLabel1);  f.setSize(300, 300);   f.setLayout(null);  f.setVisible(true);   > > 

      Java setFont

      Using setFont() and Font.createFont() to Set a Custom Font

      In this example, we set a custom font, unlike the first program where we already set the font in the class.

      To get the custom font, we download it and store it in the root of our project directory. We use the oswald.ttf font file in this example.

      We create a JLabel and initialize it to get the font file we call BufferedInputStream and pass an object of FileInputStream that takes the font file’s path as an argument. Now we get an object of InputStream .

      To create a new font, we call createFont() from the Font class and pass the font resource type as the first argument and the InputStream as the second argument. We set the custom font to the JLabel component using the deriveFont() method.

      After all of that, now we add the component to the JFrame . The output shows the custom font.

      package sample;  import javax.swing.*; import java.awt.*; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream;  public class Main    public static void main(String[] args)   JFrame f = new JFrame("Set Font Example");  JLabel jLabel;   jLabel = new JLabel("Label with a Custom Font");   try   InputStream inputStream = new BufferedInputStream(  new FileInputStream("oswald.ttf"));   Font font = Font.createFont(Font.TRUETYPE_FONT, inputStream);   jLabel.setFont(font.deriveFont(Font.BOLD, 12f));   > catch (FontFormatException | IOException e)   e.printStackTrace();  >   jLabel.setBounds(80, 100, 120, 30);   f.add(jLabel);  f.setSize(300, 300);   f.setLayout(null);  f.setVisible(true);   > > 

      Java setFont

      Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

      Related Article — Java Swing

      Related Article — Java JLabel

      Copyright © 2023. All right reserved

      Источник

      How to change font in Java gui application?

      I wanted to change the font in my Java GUI application. Currently I am using Font newFont = new Font(«Serif», Font.BOLD, 24);. To change the font. How can I use fonts like ‘comic sans’ or ‘calibri’ in my GUI based application in Java ? Currently I am using jdk 1.60.

      2 Answers 2

      You could start by listing the available font names using something like.

      String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); for (int i = 0; i

      This a great little way of checking the font names.

      If you did this, you would find that «Comic Sans» is listed as «Comic Sans MS», this means you’ll need to use something like new Font(«Comic Sans MS», Font.PLAIN, 24) to create a new font

      Font

      Showing: Comic Sans MS, Calibri, Look and feel default

      public class TestPane extends JPanel < public TestPane() < setLayout(new GridBagLayout()); JLabel label = new JLabel("Hello"); label.setFont(new Font("Comic Sans MS", Font.PLAIN, 24)); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; add(label, gbc); label = new JLabel("Hello"); label.setFont(new Font("Calibri", Font.PLAIN, 24)); add(label, gbc); label = new JLabel("Hello"); Font font = label.getFont(); label.setFont(font.deriveFont(Font.PLAIN, 24f)); add(label, gbc); >@Override public Dimension getPreferredSize() < return new Dimension(200, 200); >> 

      Источник

      Читайте также:  Auto fill auto fit css grid
Оцените статью