[Swing]将相同标签添加到面板中的不同位置,无需复制

[Swing]Add same label to different location in a panel, without copying

我有一个应用程序计算一周中所有 7 天的打卡时间。我的打算,就是让用户介绍每天的进出hours/minutes,然后收集这些数据做计算。

UI 部分应该是这样的:

Monday:     mondayEntryHour   :   mondayEntryMinutes       mondayLeaveHour   :   mondayLeaveMinutes        
Tuesday:   tuesdayEntryHour   :   tuesdayEntryMinutes     tuesdayLeaveHour   :   tuesdayLeaveMinutes
....

我收集数据的所有地方都是 JTextFields,它们之间的 :JLabel。所有 14 个标签都具有相同的内容、相同的字体和样式,但我无法创建相同的变量并将其添加到所有需要的地方 14 次,因为它只是最后一次添加。

为了证明我说的,我这里有个SCCEE:

import java.awt.Cursor;
import java.awt.EventQueue;

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

import net.miginfocom.swing.MigLayout;

public class RepeatedJLabel extends JFrame {
    public RepeatedJLabel() {
        run();

    }

    public void run() {
        JPanel p = new JPanel();
        p.setLayout(new MigLayout("debug, fill", "[grow]", "[]10[]10[]"));

        JLabel label = new JLabel("MY LABEL 1");
        p.add(label, "cell 0 1, grow");
        p.add(label, "cell 0 2, grow");
        p.add(label, "cell 0 3, grow");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        getContentPane().add(p);

        setVisible(true);
        setLocationRelativeTo(null);
        setResizable(true);
        pack();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                RepeatedJLabel test = new RepeatedJLabel();

            }
        });
    }
}

我必须为它们创建 14 个变量吗?这是愚蠢的。我不想与这个变量的 copy/shallow copy/deep 副本混在一起,因为它太简单了,不能乱来。有什么想法吗?

  1. 使用factory method创建每个JLabel:

    private static JLabel newLabel() {
        return new JLabel("MY LABEL 1");
    }
    
  2. 每次使用for循环添加JLabel

    final int amountOfLabels = 3;
    for(int i = 0; i < amountOfLabels; i++) {
        panel.add(newLabel(), "cell 0 " + i + ", grow");
    }