2010-05-20 102 views
0

對於作業,我試圖創建一個具有框架的「CustomButton」,並在該框架中繪製兩個三角形和一個正方形。它應該給用戶一個按下按鈕後的效果。因此,對於初學者,我試圖設置起始圖形,繪製兩個三角形和一個正方形。我遇到的問題是,雖然我將框架設置爲200,200,並且我繪製的三角形被認爲是我的框架尺寸的正確結尾,但是當我運行該程序時,我必須擴展窗口以製作整個作品,我的「CustomButton」可見。這是正常的嗎?謝謝。簡單的框架和圖形幫助

代碼:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 


public class CustomButton 
{ 
    public static void main(String[] args) 
    { 
     EventQueue.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       CustomButtonFrame frame = new CustomButtonFrame(); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setVisible(true); 
      } 
     }); 
    } 
} 

class CustomButtonFrame extends JFrame 
{ 
    // constructor for CustomButtonFrame 
    public CustomButtonFrame() 
    { 
     setTitle("Custom Button"); 
     setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 
     CustomButtonSetup buttonSetup = new CustomButtonSetup(); 
     this.add(buttonSetup); 
    } 

    private static final int DEFAULT_WIDTH = 200; 
    private static final int DEFAULT_HEIGHT = 200; 

} 

class CustomButtonSetup extends JComponent 
{ 
    public void paintComponent(Graphics g) 
    { 
     Graphics2D g2 = (Graphics2D) g; 

     // first triangle coords 
     int x[] = new int[TRIANGLE_SIDES]; 
     int y[] = new int[TRIANGLE_SIDES]; 
     x[0] = 0; y[0] = 0; 
     x[1] = 200; y[1] = 0; 
     x[2] = 0; y[2] = 200; 
     Polygon firstTriangle = new Polygon(x, y, TRIANGLE_SIDES); 

     // second triangle coords 
     x[0] = 0; y[0] = 200;  
     x[1] = 200; y[1] = 200; 
     x[2] = 200; y[2] = 0; 
     Polygon secondTriangle = new Polygon(x, y, TRIANGLE_SIDES); 

     g2.drawPolygon(firstTriangle); 
     g2.setColor(Color.WHITE); 
     g2.fillPolygon(firstTriangle); 

     g2.drawPolygon(secondTriangle); 
     g2.setColor(Color.GRAY); 
     g2.fillPolygon(secondTriangle); 

     // draw rectangle 10 pixels off border 
     g2.drawRect(10, 10, 180, 180); 

    } 
    public static final int TRIANGLE_SIDES = 3; 
} 

回答

1

嘗試增加

public Dimension getPreferredSize() { 
    return new Dimension(200, 200); 
} 

您CustomButtonSetup類。

然後做

setTitle("Custom Button"); 
    //setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 
    CustomButtonSetup buttonSetup = new CustomButtonSetup(); 
    this.add(buttonSetup); 
    pack(); 

(從API-Google文檔pack() :)

此窗口的大小,以適合其子組件的首選大小和佈局。

你應該得到的東西,如:

enter image description here

+0

將首選維存儲在靜態變量中並將其返回到getPreferredSize()中會更好。否則,每次調用getPreferredSize()時都會創建一個新實例,並且這可能會經常發生,具體取決於佈局。 – 2010-05-20 07:32:11

+0

好點。更好的解決方案可能是在組件的構造函數中執行'setPreferredSize()'。希望OP閱讀此內容。 – aioobe 2010-05-20 07:35:28

1

DEFAULT_WIDTHDEFAULT_HEIGHT您設置是整個幀,包括邊框,窗口標題,圖標等。這不是大小繪圖畫布本身。因此,如果您在200x200的畫布中繪製某些東西,則預計它不一定適合包含該畫布的200x200窗口。