Java窗口中的文字显示方框

1. 前言

在Java中,我们可以使用各种图形库来创建窗口应用程序。其中,文字的显示是窗口应用程序中非常基础且常见的功能之一。在本文中,我们将介绍如何在Java窗口中显示文字,并使用方框将文字包围起来。通过本文的学习,读者将能够掌握如何在Java窗口中实现文字的显示和样式设置。

2. 文字显示

在Java中,我们可以使用JFrameJLabel等组件来创建窗口应用程序,并在窗口中显示文字。以下是一个简单的示例代码:

import javax.swing.JFrame;
import javax.swing.JLabel;

public class TextDisplayExample extends JFrame {
    public TextDisplayExample() {
        JLabel label = new JLabel("Hello, World!");
        add(label);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new TextDisplayExample();
    }
}

在上述代码中,我们创建了一个继承自JFrame的类TextDisplayExample。在该类的构造函数中,我们创建了一个JLabel组件,并将其添加到窗口中。JLabel是一个用于显示文本的标签组件,我们可以将需要显示的文字作为参数传递给它的构造函数。然后,我们通过add方法将JLabel添加到窗口中。最后,我们对窗口进行了一些基本的设置,并将其显示出来。

3. 文字样式设置

除了显示文字外,我们还可以对文字的样式进行设置,包括字体、大小、颜色等。在Java中,我们可以使用Font类和Color类来实现这些样式设置。

3.1 字体设置

要设置文字的字体,我们首先需要创建一个Font对象,并将其作为参数传递给JLabel的构造函数。以下是一个示例代码:

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;

public class FontExample extends JFrame {
    public FontExample() {
        JLabel label = new JLabel("Hello, World!");
        Font font = new Font("Arial", Font.BOLD, 20);
        label.setFont(font);
        add(label);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new FontExample();
    }
}

在上述代码中,我们创建了一个Font对象,并将其设置为粗体、大小为20的Arial字体。然后,我们将该字体对象设置给JLabel组件,实现了文字样式的设置。

3.2 大小设置

要设置文字的大小,我们可以通过Font对象的构造函数或setSize方法来实现。以下是一个示例代码:

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;

public class SizeExample extends JFrame {
    public SizeExample() {
        JLabel label = new JLabel("Hello, World!");
        Font font = new Font("Arial", Font.PLAIN, 30);
        label.setFont(font);
        add(label);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new SizeExample();
    }
}

在上述代码中,我们将文字的大小设置为30,并将其应用于JLabel组件。

3.3 颜色设置

要设置文字的颜色,我们可以使用Color类。以下是一个示例代码:

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;

public class ColorExample extends JFrame {
    public ColorExample() {
        JLabel label = new JLabel("Hello, World!");
        Font font = new Font("Arial", Font.PLAIN, 20);
        label.setFont(font);
        label.setForeground(Color.RED); // 设置文字颜色为红色
        add(label);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new ColorExample();
    }
}

在上述代码中,我们使用setForeground方法将文字的颜色设置为红色。

4. 方框样式设置

要在文字周