[Java] Use the Swing component pop-up window to display the ninety-nine multiplication table


1. Effect display

Go directly to the renderings first:insert image description here

2. Complete code

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

public class MultiplicationTable extends JFrame {
    
    

    public static void main(String[] args) {
    
    
        // 创建并显示窗口
        new MultiplicationTable().setVisible(true);
    }

    public MultiplicationTable() {
    
    
        // 设置窗口标题
        setTitle("九十九乘法表");
        // 设置窗口大小
        setSize(1400, 800);
        // 设置窗口关闭操作
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        // 将窗口放置在屏幕中心
        setLocationRelativeTo(null);
        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane();
        // 创建并添加乘法表面板
        scrollPane.setViewportView(new TablePanel());
        // 添加滚动面板
        add(scrollPane);
    }
}

class TablePanel extends JPanel {
    
    

    public TablePanel() {
    
    
        // 设置布局管理器
        setLayout(new GridBagLayout());
        // 设置网格约束
        GridBagConstraints constraints = new GridBagConstraints();
        // 设置间距
        constraints.insets = new Insets(5, 5, 5, 5);
        // 循环创建标签
        for (int i = 1; i < 100; i++) {
    
    
            for (int j = 1; j <= i; j++) {
    
    
                // 计算乘积
                int product = i * j;
                // 创建标签
                JLabel label = new JLabel(j + " x " + i + " = " + product);
                // 设置字体
                label.setFont(new Font("Arial", Font.BOLD, 20));
                // 设置网格约束
                constraints.gridx = j - 1;
                constraints.gridy = i - 1;
                // 添加标签
                add(label, constraints);
            }
        }
    }
}


3. Code ideas

       First, I created a window (JFrame) using Java's Swing components. A panel (JPanel) was then added to the window to store the various parts of the multiplication table.

       In this panel, a layout manager is used to control how the multiplication table is arranged. And the GridBagLayout layout manager is used, which can control the size and position of each cell by setting grid constraints.

       In order to display each formula of the multiplication table, I also created a label (JLabel), placed the label in the cell of the panel, and set the font and font size.

       Finally, a scroll panel (JScrollPane) is added to allow scrolling when the content exceeds the bounds of the window.


				  本文到此结束,谢谢大家的浏览。

Guess you like

Origin blog.csdn.net/weixin_57807777/article/details/128433703