在上一篇成功建立了視窗,這篇要做視窗頂部標題。
JFrame frame = new JFrame("Tic-Tac-Toe"); //加上標題
JLabel textLabel = new JLabel();
JPanel textPanel = new JPanel();
說明:
JLabel textLabel:用來渲染文字內容的標籤元件。
JPanel textPanel:用來承載標籤的容器面板。
// 設定文字標籤的視覺樣式
textLabel.setBackground(Color.darkGray); // 設定背景為深灰色
textLabel.setForeground(Color.white); // 設定字體顏色為白色
textLabel.setFont(new Font("Arial", Font.BOLD, 50)); // 設定字型為 Arial、粗體、字級 50
textLabel.setHorizontalAlignment(JLabel.CENTER); // 文字置中對齊
textLabel.setText("Tic-Tac-Toe"); // 設定顯示文字
textLabel.setOpaque(true); // 設定為不透明,背景顏色才能正確顯示出來
// 將文字標籤加入面板,再將面板置於視窗上方
textPanel.setLayout(new BorderLayout());
textPanel.add(textLabel);
frame.add(textPanel, BorderLayout.NORTH); // 放置在視窗北側(頂部)
跑出來長這樣:
參考教學影片:https://youtu.be/Nc77ymnm8Ss?si=pfxGmhwdb3I0nLJu