gpt4 book ai didi

Java JFrame .setSize(x, y) 不工作?

转载 作者:行者123 更新时间:2023-11-29 05:43:57 25 4
gpt4 key购买 nike

当我执行这段代码时,会弹出一个小窗口,里面大约是 116x63,包括边框在内的整个尺寸约为 140x100。如何将内部设置为我需要的样子?

public static void graphics() {
JFrame frame = new JFrame();

String title = "test window";
frame.setTitle(title);

frame.setSize(gridRow, gridCol); //101 x 101
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

最佳答案

  1. 创建一个自定义组件,从 JPanel 扩展,覆盖其 getPreferredSize 方法以返回您想要的窗口大小。
  2. 将其添加到您的框架或将其设置为框架的内容 Pane 。
  3. 在框架上调用pack

更新示例

enter image description here

在我的电脑上,Frame size = java.awt.Dimension[width=216,height=238]

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestFrameSize01 {

public static void main(String[] args) {
new TestFrameSize01();
}

public TestFrameSize01() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

System.out.println("Frame size = " + frame.getSize());
}
});
}

public class TestPane extends JPanel {

public TestPane() {
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
String text = getWidth() + "x" + getHeight();
FontMetrics fm = g2d.getFontMetrics();
int x = (getWidth() - fm.stringWidth(text)) / 2;
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g2d.drawString(text, x, y);
g2d.dispose();
}
}
}

关于Java JFrame .setSize(x, y) 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16473627/

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