2010-03-23 85 views
0

我想要做一個JPanel一些圖紙,但封閉的JFrame大小似乎並不匹配,我問過要繪製的座標。爲什麼我的座標不符合我的JFrame大小?

在我的示例代碼中,JFrame大小設置爲(700,700),最後一點繪製在(600,600)。我希望這一點可以從右邊緣和底部邊緣抽取100個像素,但不是(請參閱屏幕截圖)。

alt text

下面是我使用的代碼:

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); 


    } 

} 

回答

2

只是一種猜測:

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); 

    } 
+0

謝謝,我不知道關於pack方法。爲了使它工作,你必須設置scratchSize爲scratch,但幾乎你所說的。 – 2010-03-23 12:17:45

+0

我認爲,關鍵是不僅包,但設置劃痕/面板的大小在框架代替。 – extraneon 2010-03-23 12:24:59

3

你的JFrame可能是700x700如果包括窗口裝飾。由於您的paintComponent()方法屬於您的JFrame中的面板,因此所有項目都將以面板左上角的原點繪製,而不是JFrame的左上角。

可能的解決方法是讓面板700x700並使JFrame相應地調整大小。

+0

燁,包括標題欄架是我的Mac上正好700像素。 – extraneon 2010-03-23 12:23:39

相關問題