Javaexamples-gui-font

提供:Dev Guides
移動先:案内検索

Javaの例-テキストを異なるフォントで表示する

問題の説明

異なるフォントでテキストを表示する方法は?

溶液

次の例は、FontクラスのsetFont()メソッドを使用して、異なるフォントでテキストを表示する方法を示しています。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main extends JPanel {
   String[] type = { "Serif","SansSerif"};
   int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD, Font.ITALIC + Font.BOLD };
   String[] stylenames = { "Plain", "Italic", "Bold", "Bold & Italic" };

   public void paint(Graphics g) {
      for (int f = 0; f < type.length; f++) {
         for (int s = 0; s < styles.length; s++) {
            Font font = new Font(type[f], styles[s], 18);
            g.setFont(font);
            String name = type[f] + " " + stylenames[s];
            g.drawString(name, 20, (f *4 + s + 1)* 20);
         }
      }
   }
   public static void main(String[] a) {
      JFrame f = new JFrame();
      f.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
      f.setContentPane(new Main());
      f.setSize(400,400);
      f.setVisible(true);
   }
}

結果

上記のコードサンプルは、次の結果を生成します。

Different font names are displayed in a frame.

以下は、異なるフォントでテキストを表示する別のサンプル例です

import java.awt.*;
import javax.swing.*;

public class Main extends JComponent {
   String[] dfonts;
   Font[] font;
   static final int IN = 15;
   public Main() {
      dfonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
       font = new Font[dfonts.length];
   }
   public void paintComponent(Graphics g) {
      for (int j = 0; j < dfonts.length; j += 1) {
         if (font[j] == null) {
            font[j] = new Font(dfonts[j], Font.PLAIN, 16);
         }
         g.setFont(font[j]);
         int p = 15;
         int q = 15+ (IN * j);
         g.drawString(dfonts[j],p,q);
      }
   }
   public static void main(String[] args) {
      JFrame frame = new JFrame("Different Fonts");
      frame.getContentPane().add(new JScrollPane(new Main()));
      frame.setSize(350, 650);
      frame.setVisible(true);
   }
}