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 大小不正确
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01