JFrame 大小不正确

JFrame not correct size(JFrame 大小不正确)

本文介绍了JFrame 大小不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 创建一个乒乓球游戏.我最初有一个 未装饰 JFrame,其 width700height400.后来我改变了主意,改用装饰框架.错误是球屏幕离开装饰框架中的顶部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 大小不正确

基础教程推荐