Font size in java swing

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) — получить глифы, выполняя повозможности полное расположение текста. Метод нужен для языков со сложным алфавитом как арабский и хинди.

      Источник

      How to change JLabel font style and size in Java

      Hello folks! In this tutorial, we will discuss how to change the JLabel font style and font size in Java. I will discuss thoroughly each of them. Firstly, let us discuss changing of JLabel font style in Java.

      How to change JLabel font style in Java

      We import the Java Swing and Java AWT libraries into our code and use them.

      • Java Swing library is used for creating lightweight windows and it provides various powerful components such as JFrame, JLabel, etc.
      • Java AWT Library contains all the necessary classes needed to develop a GUI (Graphical User Interface).

      Let us walk through the code and understand it better.

      Firstly, We are creating a JFrame with the title “JLabel Font Style Example”. The setBounds() function is used to specify the bounds of the frame for easier visualization. The first two parameters are the (x,y) i.e., the location of the frame, and the other two parameters indicate the height and width of the frame respectively.

      Now, we create a container to add our objects to the frame. We create a JLabel object with the title “Welcome!” and name it obj1. We use Object.setFont() function to set the Font Style of our text. For, the first object, the font style is set to “Arial”.

      Then, we create another JLabel object (obj2) the same as before but with a font style as “Times New Roman” and add both objects to the container frame and display it.

      Let’s see the code:

      //Necessary Imports import java.awt.*; import javax.swing.*; public class FontSyle extends JFrame < public static void main(String[] args) < JFrame frame = new JFrame("JLabel Font Style Example"); // Creating a new JFrame with a title frame.setLayout(null); // To terminate the default flow layout frame.setVisible(true); // To display the frame frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // To Terminate JFrame and the program on close frame.setBounds(100, 200, 400, 400); // To set the bounds of the frame. Container c = frame.getContentPane(); //To get content pane layer and add objects in the frame. //Creating First JLabel Object JLabel obj1 = new JLabel("Welcome!"); //Creating a JLabel with title as Welcome obj1.setBounds(100, 100, 300, 30); //Setting the bounds of the label. obj1.setFont(new Font("Arial", Font.PLAIN, 30)); //Creating an Arial Font Style with size 30 //Creating Second Jlabel Object with different font JLabel obj2 = new JLabel("Welcome!"); //Creating same JLabel title as before. obj2.setBounds(100, 200, 300, 30); //Setting the same bounds as before. obj2.setFont(new Font("Times New Roman", Font.PLAIN, 30)); //Creating an Times New Roman Font Style with size 30 //Adding the objects in the container frame c.add(obj1); c.add(obj2); >>

      How to change JLabel font style in Java

      From, the above output we can see that the first text is in “Arial” font and the second text in “Times New Roman” font with the same font size as 30. Thus, in this way, we can change the JLabel font style in Java.

      How to change JLabel font size in Java

      We use various parameters of the Font() function to change the font size of JLabel. The Font() function has three parameters as Font Style, Font Weight, and Font Size. We change the Font Size parameter to change the size of the JLabel Font.

      The use of the Font() function is shown below:

      Object.setFont(new Font("Font-Style", Font-Weight, Font Size));

      We use the same code as above keeping font styles the same while changing only the font size. We create a JLabel object (obj1) and assign a font size of 16 and another JLabel object (obj2) with a font size of 30.

      Let’s see the code:

      //Necessary Imports import java.awt.*; import javax.swing.*; public class FontSize extends JFrame < public static void main(String[] args) < JFrame frame = new JFrame("JLabel Font Size Example"); // Creating a new JFrame with a title frame.setLayout(null); // To terminate the default flow layout frame.setVisible(true); // To display the frame frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // To Terminate JFrame and program on close frame.setBounds(100, 200, 400, 400); // To set the bounds of the frame. Container c = frame.getContentPane(); //To get content pane layer and add objects in the frame. //Creating First JLabel Object JLabel obj1 = new JLabel("Welcome!"); //Creating a JLabel with title as Welcome obj1.setBounds(100, 100, 300, 30); //Setting the bounds of the label. obj1.setFont(new Font("Arial", Font.PLAIN, 16)); //Creating an Arial Font Style with size 16 //Creating Second Jlabel Object with different font JLabel obj2 = new JLabel("Welcome!"); //Creating same JLabel title as before. obj2.setBounds(100, 200, 300, 30); //Setting the same bounds as before. obj2.setFont(new Font("Arial", Font.PLAIN, 30)); //Creating an Arial Font Style but with size 30 //Adding the objects in the container frame c.add(obj1); c.add(obj2); >>

      How to change JLabel font size in Java

      From, the above output we can see that the first text is in “Arial” font style with a size of 16 and the second text with the same font style but with a font size of 30. Thus, in this way, we can change the JLabel font size in Java.

      Thanks for reading. I hope you found this post useful!

      Источник

      Читайте также:  Php case when then
Оцените статью