2010-05-20 112 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窗口。