gpt4 book ai didi

java - 如何在较大的 jframe 上居中放置小 Canvas

转载 作者:行者123 更新时间:2023-11-29 05:03:51 24 4
gpt4 key购买 nike

Like the title says, i am looking to center a 800x600 canvas on a 1920x1080 screen enter image description here 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
  • 在不使用 GridBagConstraints 的情况下将您的组件、您的绘图 JPanel(不是 Canvas)添加到容器中。默认情况下,它会将其添加到容器的居中位置。
  • 如果您像许多人告诉您的那样使用 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();
}
});
}
}

关于java - 如何在较大的 jframe 上居中放置小 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31082333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com