如何在较大的 jframe 上居中一个小 canvas

How to center a small canvas on a larger jframe

Like the title says, i am looking to center a 800x600 canvas on a 1920x1080 screen I want the canvas to be centered in the JFrame

public class Window extends JFrame {

    private static final long serialVersionUID = 7045103465799258651L;
    Dimension d;


    public Window(int w, int h, String title,Launcher launch){
        setTitle(title);

        d = new Dimension(w,h);
        setMinimumSize(d);
        setMaximumSize(d);
        setPreferredSize(d);

        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        pack();

        setFocusable(true);

        setLocationRelativeTo(null);

        add(launch);
        launch.start();
    }

}

一种方式:

  • 给你的容器一个 GridBagLayout
  • 将您的组件、绘图 JPanel(不是 Canvas)添加到容器中,而不使用 GridBagConstraints。它会默认将其添加到容器中的居中位置。
  • 如果您像许多人告诉您的那样使用 BorderLayout,您的组件将 填充 容器,这似乎不是您的目标。

例如:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.*;

public class TestCenterLayout extends JPanel{
   private static final long serialVersionUID = 1L;
   private static final int PREF_W = 800;
   private static final int PREF_H = 600;
   private static final Color BACKGROUND = Color.pink;

   public TestCenterLayout() {
      setBorder(BorderFactory.createTitledBorder("800 x 600 Panel"));
      setBackground(BACKGROUND);
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("Test Center Layout");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().setLayout(new GridBagLayout());
      frame.getContentPane().add(new TestCenterLayout());
      frame.pack();
      frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}