我正在制作时钟应用程序,但是我似乎无法使时钟位于窗口的中间(无论窗口的大小如何)。我正在考虑使用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();
}
}