Как изменить шрифт java swing

I was wondering how to set the default font for my entire Java swing program. From my research it appears it can be done with UIManager, something to do with LookAndFeel, but I can't find specifica...

As a completion of @Amir answer, this is the complete list of keys

I use this function

private void setFont(FontUIResource myFont) {
    UIManager.put("CheckBoxMenuItem.acceleratorFont", myFont);
    UIManager.put("Button.font", myFont);
    UIManager.put("ToggleButton.font", myFont);
    UIManager.put("RadioButton.font", myFont);
    UIManager.put("CheckBox.font", myFont);
    UIManager.put("ColorChooser.font", myFont);
    UIManager.put("ComboBox.font", myFont);
    UIManager.put("Label.font", myFont);
    UIManager.put("List.font", myFont);
    UIManager.put("MenuBar.font", myFont);
    UIManager.put("Menu.acceleratorFont", myFont);
    UIManager.put("RadioButtonMenuItem.acceleratorFont", myFont);
    UIManager.put("MenuItem.acceleratorFont", myFont);
    UIManager.put("MenuItem.font", myFont);
    UIManager.put("RadioButtonMenuItem.font", myFont);
    UIManager.put("CheckBoxMenuItem.font", myFont);
    UIManager.put("OptionPane.buttonFont", myFont);
    UIManager.put("OptionPane.messageFont", myFont);
    UIManager.put("Menu.font", myFont);
    UIManager.put("PopupMenu.font", myFont);
    UIManager.put("OptionPane.font", myFont);
    UIManager.put("Panel.font", myFont);
    UIManager.put("ProgressBar.font", myFont);
    UIManager.put("ScrollPane.font", myFont);
    UIManager.put("Viewport.font", myFont);
    UIManager.put("TabbedPane.font", myFont);
    UIManager.put("Slider.font", myFont);
    UIManager.put("Table.font", myFont);
    UIManager.put("TableHeader.font", myFont);
    UIManager.put("TextField.font", myFont);
    UIManager.put("Spinner.font", myFont);
    UIManager.put("PasswordField.font", myFont);
    UIManager.put("TextArea.font", myFont);
    UIManager.put("TextPane.font", myFont);
    UIManager.put("EditorPane.font", myFont);
    UIManager.put("TabbedPane.smallFont", myFont);
    UIManager.put("TitledBorder.font", myFont);
    UIManager.put("ToolBar.font", myFont);
    UIManager.put("ToolTip.font", myFont);
    UIManager.put("Tree.font", myFont);
    UIManager.put("FormattedTextField.font", myFont);
    UIManager.put("IconButton.font", myFont);
    UIManager.put("InternalFrame.optionDialogTitleFont", myFont);
    UIManager.put("InternalFrame.paletteTitleFont", myFont);
    UIManager.put("InternalFrame.titleFont", myFont);
}

and i call it in main before invoking the ui

setFont(new FontUIResource(new Font("Cabin", Font.PLAIN, 14)));

For a complete list of Swing UI Manager keys check this link

Java различает два типа шрифтов: физические и логические.

Физический шрифт является библиотекой содержащей образы символов (т.е. глифы) и таблицы отображения последовательности символов в последовательность глифов. Всегда гарантировано отображение TrueType шрифтов, поддержка других технологий зависит от реализации java.

Также гарантировано отображение пяти логических шрифтов обозначающих пять семейств шрифтов: Serif, SansSerif, Monospaced, Dialog и DialogInput. В отличие от физических шрифтов они не содержат образы символов, а используют физические шрифты для их отображения. По этой причине логические шрифты могут выглядеть по разному.

Сам шрифт описывается классом Font. Ниже приведено простое использование шрифта.

public class MyComponent extends JComponent {

    private static final long serialVersionUID = 1L;
    private Font f1 = new Font("TimesRoman", Font.BOLD, 22), 
            f2 = new Font("Courier", Font.ITALIC, 10), 
            f3 = new Font("Arial", Font.BOLD + Font.ITALIC, 16); 
    private String str = "Hello World";

    public MyComponent() {
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Dimension d = getSize(null);
        g2.setBackground(Color.gray);
        g2.clearRect(0, 0, d.width, d.height);
        g2.setColor(Color.cyan);

        // выводим строку тремя разными шрифтами
        g2.setFont(f1);
        g2.drawString(str, 10, 30);
        g2.setFont(f2);        
        g2.drawString(str, 10, 60);
        g2.setFont(f3);        
        g2.drawString(str, 10, 90);
    }
}

имя шрифта

Шрифт может иметь несколько обликов как жирный, наклонный, готический или обычный. Все эти облики имеют одинаковый типографический дизайн. Таким образом, к шрифту применимо три имени: логическое имя шрифта, имя облика шрифта или попросту имя шрифта (например, Helvetica Bold), и имя семейства шрифтов, определяющее типографический дизайн (например, Helvetica). Для получения имен в классе Font определены следующие методы:

  • getFamily() — имя семейства данного шрифта;
  • getFamily(Locale l) — локализованное имя семейства данного шрифта;
  • getFontName() — имя облика шрифта;
  • getFontName(Locale l) — локализованное имя облика шрифта;
  • getName() — логическое имя шрифта;
  • getPSName() — посткрипт имя шрифта.

создание шрифтов

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

  • decode(String str) — статический метод создающий шрифт по строке описания, например вызов с аргументом «Arial-BOLD-18» аналогично конструктору new Font(«Arial», Font.BOLD, 18). Строка может принимать один из следующий форматов:
    • имя_шрифта-стиль-размер
    • имя_шрифта-стиль
    • имя_шрифта-размер
    • имя_шрифта стиль размер
    • имя_шрифта стиль
    • имя_шрифта размер
    • имя_шрифта
  • getFont(String nm) — статический метод для получения шрифта из системного списка свойств (см. System.getProperties()), значение того свойства будет интерпретироваться как объект типа Font через метод decode;
  • getFont(String nm, Font font) — аналогично предыдущему, но если свойство не найдено то будет возвращен указанный шрифт;
  • deriveFont(AffineTransform trans) — создает из текущего шрифта новый, применяя указанную трансформацию;
  • deriveFont(float size) — создает из текущего шрифта новый, применяя указанный размер;
  • deriveFont(int style) — создает из текущего шрифта новый, применяя указанный стиль;
  • deriveFont(int style, AffineTransform trans) — создает из текущего шрифта новый, применяя указанные стиль и трансформацию;
  • deriveFont(int style, float size) — создает из текущего шрифта новый, применяя указанные стиль и размер;
  • deriveFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes) — создает из текущего шрифта новый, применяя указанные атрибуты;
  • getFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes) — статический метод создающий шрифт с указанными атрибутами;
  • createFont(int fontFormat, File fontFile) — статический метод, создающий шрифт указанного типа (значение FONT.TRUETYPE) из указанного файла.

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

  • 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 — базовая линия, используемая в алфавитах сходных с деванагари;
  • getBaselineOffsets() — массив смещений всех типов базовых линий относительно
    базовой линии текста. Например, если базовая линия текста CENTER_BASELINE, то
    getBaselineOffsets()[CENTER_BASELINE] будет равно 0 т.е. нулевое смещение;
  • getStrikethroughOffset() — смещение зачеркивающей линии относительно базовой линии;
  • getStrikethroughThickness() — толщина зачеркивающей линии;
  • getUnderlineOffset() — смещение линии подчеркивания относительно базовой линии;
  • getUnderlineThickness() — толщина линии подчеркивания.

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

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

sadiul hakim

Hello there, I am back again.

Today i am going to show you how you can use custom font or how you can customize your fonts in java swing.So, Let’s get started…

First we need to create a Frame..

import javax.swing.JFrame;

public class CustomFont extends JFrame{

    public CustomFont()  {
        this.setBounds(300,100,400,300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        CustomFont frame=new CustomFont();
        frame.setVisible(true);
    }
}

Enter fullscreen mode

Exit fullscreen mode

java
This will create a nice frame.

I do not want to use any Layout for that i need to add this line in the Constructor

this.setLayout(null);

Enter fullscreen mode

Exit fullscreen mode

Now i want to use custom font in a textField.For that i need to create a field.

First import JTextField

import javax.swing.JTextField;

Enter fullscreen mode

Exit fullscreen mode

Declare textField as a private class field

private JTextField text;

Enter fullscreen mode

Exit fullscreen mode

Now create and add textField to the frame

text=new JTextField();
text.setBounds(20,20,150,30);
add(text);

Enter fullscreen mode

Exit fullscreen mode

Now i want to customize this fields font
For that i need to create an instance of Font class.You can create an instance of font class like this.

First import Font class

import java.awt.Font;

Enter fullscreen mode

Exit fullscreen mode

Then

Font font=new Font("Fira Code",Font.PLAIN,12);

Enter fullscreen mode

Exit fullscreen mode

First you need to give Font Name then Font Style and Font size.Now you need to add the font to the field.

 text.setFont(font);

Enter fullscreen mode

Exit fullscreen mode

Now your field should have a customized font.

  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

Using setFont in Java

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);

    }
}

Output:

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);

    }
}

Output:

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);

    }
}

Output:

Java setFont

9 / 9 / 16

Регистрация: 07.03.2014

Сообщений: 202

1

27.08.2015, 17:40. Показов 14555. Ответов 3


Чтобы надпись на кнопке была нужного мне размера

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



kot96

54 / 45 / 97

Регистрация: 17.08.2014

Сообщений: 157

28.08.2015, 13:31

2

Лучший ответ Сообщение было отмечено Nikakula как решение

Решение

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
 
public class ss {
 
    ss(){
        JFrame jfrm = new JFrame();
        jfrm.setLayout(new FlowLayout());
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jfrm.setSize(100, 100);
        
        Font BigFontTR = new Font("TimesRoman", Font.BOLD, 30);//Тут все про шрифт)
        
        JButton jbtn = new JButton("Text");
        
        jbtn.setFont(BigFontTR);//применяем шрифт к кнопке
        
        jfrm.add(jbtn);
        jfrm.setVisible(true);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                new ss();
            }
        });
 
    }
 
}



1



-13 / 5 / 0

Регистрация: 28.08.2015

Сообщений: 17

28.08.2015, 13:42

3

Для изменения цвета и шрифта в классе Component существуют методы setFont () и setColor (), которые применяются не только для меток, но и для любых компонентов.

В тексте метки возможно также применение HTML:

JLabel label = new JLabel («<html>» + «S <font size = -2> MALL»)



0



9 / 9 / 16

Регистрация: 07.03.2014

Сообщений: 202

30.08.2015, 19:24

 [ТС]

4

kot96, спасибо



0



Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить шрифт cambria math на times new roman
  • Как изменить шрифт blogger
  • Как изменить шрифт bdo
  • Как изменить шрифт arduino ide
  • Как изменить шорткод woocommerce

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии