Java でテキストを揃える

Sheeraz Gul 2023年10月12日
Java でテキストを揃える

クラスJava.text.Formatを拡張してテキストを整列させるクラスを作成できます。 このチュートリアルでは、Java でテキストを整列する方法を示します。

Java でテキストを揃える

Format は、数値、メッセージ、日付などの機密情報をフォーマットするための抽象基本クラスです。Text_Alignment という名前のクラスを実装します。これは、Format クラスを拡張して、テキストをフォーマットして配置できるようにします。

このクラスは、CenterRight、および Left の 3つの列挙型を定義します。これらは、後で switch 条件で指定された指示に従ってテキストを配置する場合として使用されます。 このクラスは、1 行に最大数の文字を使用し、各行を揃えます。

例を参照してください。

package delftstack;

import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class Text_Alignment extends Format {
  private static final long serialVersionUID = 1L;

  public enum Align_Text {
    LEFT,
    CENTER,
    RIGHT,
  }

  // justification for formatting
  private Align_Text Current_Alignment;

  // maximum length of a line
  private int Maximum_Chars;

  public Text_Alignment(int Maximum_Chars, Align_Text alignment) {
    switch (alignment) {
      case LEFT:
      case CENTER:
      case RIGHT:
        this.Current_Alignment = alignment;
        break;
      default:
        throw new IllegalArgumentException("invalid justification");
    }
    if (Maximum_Chars < 0) {
      throw new IllegalArgumentException("Maximum_Chars should be positive.");
    }
    this.Maximum_Chars = Maximum_Chars;
  }

  public StringBuffer format(
      Object Input_Object, StringBuffer Align_Position, FieldPosition Ignore_Position) {
    String Demo = Input_Object.toString();
    List<String> Strings_List = Split_String(Demo);
    ListIterator<String> List_Iterator = Strings_List.listIterator();

    while (List_Iterator.hasNext()) {
      String Wanted_String = List_Iterator.next();

      // put the spaces in the right place.
      switch (Current_Alignment) {
        case RIGHT:
          ALIGN(Align_Position, Maximum_Chars - Wanted_String.length());
          Align_Position.append(Wanted_String);
          break;

        case CENTER:
          int toAdd = Maximum_Chars - Wanted_String.length();
          ALIGN(Align_Position, toAdd / 2);
          Align_Position.append(Wanted_String);
          ALIGN(Align_Position, toAdd - toAdd / 2);
          break;

        case LEFT:
          Align_Position.append(Wanted_String);
          ALIGN(Align_Position, Maximum_Chars - Wanted_String.length());
          break;
      }
      Align_Position.append("\n");
    }
    return Align_Position;
  }

  protected final void ALIGN(StringBuffer Append_To, int Length) {
    for (int i = 0; i < Length; i++) Append_To.append(' ');
  }

  String format(String Demo) {
    return format(Demo, new StringBuffer(), null).toString();
  }

  // ParseObject will be required but it is not useful here.
  public Object parseObject(String Source_String, ParsePosition position) {
    return Source_String;
  }

  private List<String> Split_String(String Demo) {
    List<String> List = new ArrayList<String>();
    if (Demo == null)
      return List;
    for (int x = 0; x < Demo.length(); x = x + Maximum_Chars) {
      int End_Index = Math.min(x + Maximum_Chars, Demo.length());
      List.add(Demo.substring(x, End_Index));
    }
    return List;
  }

  public static void main(String[] args) {
    String Demo_Text =
        "DelftStack is a resource for everyone interested in programming, embedded software, and electronics."
        + "It covers the programming languages like Python, C/C++, C#, and so on in this website's first development stage."
        + "Open-source hardware also falls in the website's scope, like Arduino, Raspberry Pi, and BeagleBone."
        + "DelftStack aims to provide tutorials, how-to's, and cheat sheets to different levels of developers and hobbyists.";
    // Align Left
    Text_Alignment align = new Text_Alignment(50, Align_Text.LEFT);
    System.out.println("This is the left alignment of the given text: ");
    System.out.println(align.format(Demo_Text));

    // Align Right
    Text_Alignment align1 = new Text_Alignment(50, Align_Text.RIGHT);
    System.out.println("This is the right alignment of the given text: ");
    System.out.println(align1.format(Demo_Text));

    // Align Center
    Text_Alignment align2 = new Text_Alignment(50, Align_Text.CENTER);
    System.out.println("This is the center alignment of the given text: ");
    System.out.println(align2.format(Demo_Text));
  }
}

上記のコードは、指定されたテキストを LeftRight、および Center 配置でフォーマットします。 出力を参照してください:

This is the left alignment of the given text:
DelftStack is a resource for everyone interested i
n programming, embedded software, and electronics.
It covers the programming languages like Python, C
/C++, C#, and so on in this website's first develo
pment stage.Open-source hardware also falls in the
 website's scope, like Arduino, Raspberry Pi, and
BeagleBone.DelftStack aims to provide tutorials, h
ow-to's, and cheat sheets to different levels of d
evelopers and hobbyists.

This is the right alignment of the given text:
DelftStack is a resource for everyone interested i
n programming, embedded software, and electronics.
It covers the programming languages like Python, C
/C++, C#, and so on in this website's first develo
pment stage.Open-source hardware also falls in the
 website's scope, like Arduino, Raspberry Pi, and
BeagleBone.DelftStack aims to provide tutorials, h
ow-to's, and cheat sheets to different levels of d
                          evelopers and hobbyists.

This is the center alignment of the given text:
DelftStack is a resource for everyone interested i
n programming, embedded software, and electronics.
It covers the programming languages like Python, C
/C++, C#, and so on in this website's first develo
pment stage.Open-source hardware also falls in the
 website's scope, like Arduino, Raspberry Pi, and
BeagleBone.DelftStack aims to provide tutorials, h
ow-to's, and cheat sheets to different levels of d
             evelopers and hobbyists.
著者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook