java - 如何在 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();
}
}
解决方案
推荐阅读
- mysql - 如何将 MySQL 数据库从 AMPPS 转移到 XAMPP vm Stack
- javascript - 未捕获的类型错误:无法读取属性“值”
- colors - 在 Shopify 产品页面上显示一种颜色选项
- javascript - 需要检查登录用户名和密码,然后从以前的条目中获取数据
- arrays - 在 TypeScript 中用另一个嵌套数组对象从一个数组中查找并替换带有 id 的值
- c# - 获取匹配表达式的字典值计数的最佳方法是什么?
- c# - ASP.NET Core 5.0 OData $select 不工作
- jquery - jquery 验证复选框
- matlab - 多标签组合数据集 MATLAB 的训练、验证和测试中的混洗和分区
- python - 在 Flask 中使用块时遇到问题