2015-02-05 36 views
0

我對java還是比較新的,我一直在使用paint方法。Java:在塗料中的測量

當我學習如何使用bufferedimages,我認爲圖像尺寸爲有點過相對於框架尺寸的,所以我測試了它通過改變幀大小,以使在30寬度&高度的倍數:

int width = 1020; //34 * 30 
int height = 750; //25 * 30 
JFrame frame = new JFrame("Test"); 
GridT testGrid = new GridT(); 
frame.add(testGrid); 
frame.setSize(width, height); 

接着我有塗料的方法通過30個平方繪製的30網格,正如我懷疑,網格在邊緣切斷:

enter image description here

(注:線都是同一列或剔除,但在截圖大小調整時可能會出現不同。)

繪畫是否使用與JFrame不同的測量單位?如果是這樣,它有多少?如果不是,我可能會做錯什麼?

+0

您必須設置「GridT」的大小,而不是「JFrame」的大小。我建議你重寫'GridT'中的'getPreferredSize'方法來返回大小,因此佈局將能夠相應地調整一切。 – 2015-02-05 16:15:06

+0

您在JPanel上繪製,覆蓋paintComponent方法。您將JPanel的首選大小設置爲繪圖區域的大小。你打包JFrame。由於框架裝飾,JFrame將比您的繪圖區域更大。 – 2015-02-05 16:16:56

回答

0

您在JPanel上繪製,覆蓋paintComponent方法。您將JPanel的首選大小設置爲繪圖區域的大小。你打包JFrame。由於框架裝飾,JFrame將比您的繪圖區域更大。

您必須將2像素添加到繪圖區域的高度和寬度以查看網格。你從1,1開始;而不是0,0。

這是您的網格的一個較小的版本。

Grid Test

這裏是一個創建網格中運行的代碼。

package com.ggl.testing; 

import java.awt.BorderLayout; 
import java.awt.Dimension; 
import java.awt.Graphics; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.SwingUtilities; 

public class GridTest implements Runnable { 

    private JFrame frame; 

    @Override 
    public void run() { 
     frame = new JFrame("Grid Test"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JPanel mainPanel = new JPanel(); 
     mainPanel.setLayout(new BorderLayout()); 

     DrawingPanel drawingPanel = new DrawingPanel(); 
     mainPanel.add(drawingPanel); 

     frame.add(mainPanel); 

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

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new GridTest()); 
    } 

    public class DrawingPanel extends JPanel { 

     private static final long serialVersionUID = -5711127036945010446L; 

     private int width = 750; // 25 * 30 
     private int height = 600; // 20 * 30 

     public DrawingPanel() { 
      this.setPreferredSize(new Dimension(width + 2, height + 2)); 
     } 

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

      int x = 1; 
      int y = 1; 
      int size = 30; 

      for (int i = 0; i < 25; i++) { 
       for (int j = 0; j < 20; j++) { 
        g.drawRect(x, y, size, size); 
        y += size; 
       } 
       x += size; 
       y = 1; 
      } 
     } 
    } 

}