首页 > 解决方案 > 如何在 GridLayout Manager 的中间网格上放置组件?

问题描述

我制作了一个时钟应用程序,但我似乎无法让时钟位于窗口中间(无论窗口大小)。我正在考虑使用GridLayout管理器,但我不知道如何将它放在中间网格中。我搜索了 StackOverFlow,似乎没有人知道这个问题的答案。我会很感激帮助。

public ClockGUI()
{
    thread = new Thread(this);
    timeFormat = new SimpleDateFormat("HH:mm:ss").format(new Date());
    mainPanel();
    setup();
    thread.start();
}
private void mainPanel()
{
    mainPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    digitalDisplay = new JLabel(timeFormat);
    digitalDisplay.setFont(new Font("Arial", Font.BOLD, 100));
    digitalDisplay.setPreferredSize(new Dimension(500, 250));
    digitalDisplay.setForeground(Color.CYAN);
    startBut = new JButton("Start");

    mainPanel.add(digitalDisplay);
    mainPanel.add(startBut);
    mainPanel.setBackground(Color.BLACK);
}
private void setup()
{
    this.setTitle("Clock");
    this.add(mainPanel);
    this.setSize(600, 300);
    this.setBackground(Color.BLACK);
    this.setResizable(false);
    this.setVisible(true);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void run()
{
    for (int i = 0; i < 60; i++)
    {
        timeFormat = new SimpleDateFormat("HH:mm:ss").format(new Date());
        digitalDisplay.setText(timeFormat);
        mainPanel.removeAll();
        mainPanel.validate();
        mainPanel.repaint();
        mainPanel.add(digitalDisplay);
        mainPanel.validate();
        mainPanel.repaint();
        try
        {
            Thread.sleep(1000);

        } catch (InterruptedException e)
        {
            e.getStackTrace();
        }
    }
}

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

标签: javaswinguser-interfacelayout-managergrid-layout

解决方案


推荐阅读