如何在 Java 中使用 GridBagLayout 居中 JPanel 中的 JLabel?


用 GridBagLayout 居中 JPanel 中的元件。我們先在其中建立一個 JFrame 和 JPanel -

JFrame frame = new JFrame("Demo Frame");
JPanel panel = new JPanel();

現在,我們將新增我們的元件 -

JLabel label = new JLabel("Demo Label (Centered)");
label.setForeground(Color.white);
JCheckBox checkBox = new JCheckBox("Checkbox (Centered)");

設定佈局 -

panel.setLayout(new GridBagLayout());

以下是用 GridBagLayout 居中面板中標籤的示例 -

示例

package my;
import java.awt.Color;
import java.awt.GridBagLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Demo Frame");
      JPanel panel = new JPanel();
      JLabel label = new JLabel("Demo Label (Centered)");
      label.setForeground(Color.white);
      JCheckBox checkBox = new JCheckBox("Checkbox (Centered)");
      panel.setLayout(new GridBagLayout());
      panel.add(label);
      panel.add(checkBox);
      panel.setBackground(Color.blue);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.setSize(600, 400);
      frame.setVisible(true);
   }
}

輸出


更新於:2019 年 7 月 30 日

794 次瀏覽

啟動你的 職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.