gpt4 book ai didi

Java - 绘画时顶部插图未返回正确的值

转载 作者:行者123 更新时间:2023-12-01 17:17:40 27 4
gpt4 key购买 nike

在绘画时顶部插图没有给出正确的值有问题...我正在寻找 y 位于标题栏下方,但它无法正常工作并将其放置在距顶部 25 像素的位置作为标题栏仅占14个像素左右。

游戏框架:

import java.awt.Dimension;

import javax.swing.JFrame;


public class gameFrame extends JFrame {

static int width = 400;
static int height = 400;
static int topinset;
static int FPS = 30;

public gameFrame(){
gamePanel gamePanel = new gamePanel();
gamePanel.setPreferredSize(new Dimension(width,height));
Thread thread = new Thread(gamePanel);

this.add(gamePanel);
this.setResizable(false);
this.setSize(width, height);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);

topinset = this.getInsets().top;

thread.start();
}

public static void main(String[] args){
gameFrame gameFrame = new gameFrame();

}
}

游戏面板:

import java.awt.Graphics;

import javax.swing.JPanel;


public class gamePanel extends JPanel implements Runnable {

public gamePanel(){
this.setBounds(0,0,gameFrame.width,gameFrame.height);
this.setVisible(true);
}

@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);

g.drawString("Width: "+ gameFrame.width + " Height: " + gameFrame.height, 0, gameFrame.topinset);
}

@Override
public void run() {
while(true){
repaint();
try {Thread.sleep(1000*gameFrame.FPS);}
catch (InterruptedException e) {}
}
}

}

最佳答案

  1. 您正在面板上进行自定义绘画,因此无需担心框架的偏移。只需使用 getWidth() 和 getHeight() 方法即可获取面板的当前大小。

  2. 如果您希望面板为 (400, 400),请重写面板类的 getPreferredSize() 方法以返回该尺寸。然后使用frame.pack(),框架将适当调整自身大小以包括面板尺寸和框架装饰。

  3. 不需要静态变量。这些变量应该只是实例变量或常量。

  4. 不需要 setBounds(),因为布局管理器将确定框架中面板的大小/位置。

  5. 无需使面板可见,因为它默认可见。

  6. 遵循 Java 命名约定。类名应以大写字符开头。

  7. 你为什么要做定制绘画?为什么不直接在框架的北边添加一个 JLabel 并在标签中显示文本?

关于Java - 绘画时顶部插图未返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20833122/

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