Java 为什么不';我的坐标和我的JFrame大小不匹配吗?

Java 为什么不';我的坐标和我的JFrame大小不匹配吗?,java,jframe,Java,Jframe,我想在JPanel中绘制一些图形,但封闭的JFrame大小似乎与我要求绘制坐标的位置不匹配 在我的示例代码中,JFrame大小设置为(700700),最后一个点绘制为(600600)。我希望这一点是绘制100像素远离右边缘和下边缘,但它不是(请参阅屏幕截图) 以下是我使用的代码: import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class Scratch extend

我想在JPanel中绘制一些图形,但封闭的JFrame大小似乎与我要求绘制坐标的位置不匹配

在我的示例代码中,JFrame大小设置为(700700),最后一个点绘制为(600600)。我希望这一点是绘制100像素远离右边缘和下边缘,但它不是(请参阅屏幕截图)

以下是我使用的代码:

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Scratch extends JPanel {

    static int frameWidth = 700;
    static int frameHeight = 700;

    public static void main(String[] args) {

    JFrame frame = new JFrame();

    frame.setSize(frameWidth, frameHeight);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Scratch scratch = new Scratch();

    frame.getContentPane().add(scratch);
    
    frame.setVisible(true);

    }

    @Override
    public void paintComponent(Graphics g) {

    g.drawRect(100, 100, 1, 1);

    g.drawString("100", 100, 100);

    g.drawRect(200, 200, 1, 1);

    g.drawString("200", 200, 200);

    g.drawRect(300, 300, 1, 1);

    g.drawString("300", 300, 300);

    g.drawRect(400, 400, 1, 1);

    g.drawString("400", 400, 400);

    g.drawRect(500, 500, 1, 1);

    g.drawString("500", 500, 500);

    g.drawRect(600, 600, 1, 1);

    g.drawString("600", 600, 600);


    }

}

如果包括窗户装饰,JFrame可能是700x700。由于
paintComponent()
方法属于JFrame内的面板,因此所有项目都将以面板左上角的原点绘制,而不是JFrame的左上角


可能的解决方法是将面板设置为700x700,并相应调整JFrame的大小。

如果包含窗口装饰,JFrame可能为700x700。由于
paintComponent()
方法属于JFrame内的面板,因此所有项目都将以面板左上角的原点绘制,而不是JFrame的左上角

可能的解决方法是将面板设置为700x700,并相应调整JFrame的大小。

仅猜测:

public class Scratch extends JPanel {

    static int frameWidth = 700;
    static int frameHeight = 700;

    public static void main(String[] args) {

    JFrame frame = new JFrame();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Scratch scratch = new Scratch();
    scratch.setSize(frameWidth, frameHeight);

    frame.getContentPane().add(scratch);

    frame.pack();
    frame.setVisible(true);

    }
只是猜测:

public class Scratch extends JPanel {

    static int frameWidth = 700;
    static int frameHeight = 700;

    public static void main(String[] args) {

    JFrame frame = new JFrame();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Scratch scratch = new Scratch();
    scratch.setSize(frameWidth, frameHeight);

    frame.getContentPane().add(scratch);

    frame.pack();
    frame.setVisible(true);

    }

谢谢,我不知道打包的方法。要让它工作,你也必须为scratch设置preferredSize,但与你所说的差不多。我认为诀窍不仅在于包装,还在于设置scratch/面板的大小,而不是框架。谢谢,我不知道包装方法。为了让它正常工作,你也必须为scratch设置preferredSize,但与你所说的差不多。我认为诀窍不仅在于包装,还在于设置scratch/panel的大小,而不是框架。是的,包括标题栏,我的mac上的框架正是700px。是的,包括标题栏,我的mac上的框架正是700px。