JFrame not correct size(JFrame 大小不正确)
问题描述
我正在用 Java 创建一个乒乓球游戏.我最初有一个 未装饰 JFrame,其 width 为 700,height 为 400.后来我改变了主意,改用装饰框架.错误是球从屏幕中离开装饰框架中的顶部30px左右.我测量了屏幕,装饰后确实是700 x 400;但是,我需要将球绘制为 700 x 400 的区域,而不是整个 JFrame.我能做什么?
I am creating a pong game in Java. I originally had an undecorated JFrame with a width of 700 and a height of 400. I later changed my mind and switched to a decorated frame. The error is that the ball travels off of the screen for the top 30px or so in the decorated frame. I measured the screen, and indeed it is 700 x 400 when decorated; however, I need the area where the ball will be painted to be 700 x 400, not the entire JFrame. What can I do?
我如何设置框架的大小:
How I set the size of my frame:
this.setSize(new Dimension(WIDTH, HEIGHT));
我很高兴应要求发布解决此问题所需的所有代码.
I am happy to post all of the code needed to solve this problem upon request.
编辑
import java.awt.Dimension;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Tester extends JFrame {
public Tester() {
this.add(new Window());
pack();
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
}
private void formMouseClicked(java.awt.event.MouseEvent evt) {
System.out.println("X: " + evt.getX() + ", Y: " + evt.getY());
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Tester().setVisible(true);
}
});
}
public class Window extends JComponent {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
}
推荐答案
我能做什么?
在添加到框架的面板中进行自定义绘画.这样坐标就会如你所愿.使用这种方法的另一个好主意是重写 getPreferredSize()
以返回可查看播放区域的大小,然后 pack()
帧以使其完美的大小内容.
Do the custom painting in a panel that is added to the frame. That way the co-ordinates will be as you expect. Another good idea of using this approach is to override getPreferredSize()
to return the size of the viewable play area, then pack()
the frame to get it perfect size for the content.
这篇关于JFrame 大小不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JFrame 大小不正确


基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 大摇大摆的枚举 2022-01-01