帮助简单的框架和图形

时间:2010-05-20 06:56:37

标签: java user-interface

对于家庭作业,我正在尝试创建一个具有框架的“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;
}

2 个答案:

答案 0 :(得分: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();

(来自pack()上的api-docs:)

  

使此窗口的大小适合其子组件的首选大小和布局。

你应该得到类似的东西:

enter image description here

答案 1 :(得分:1)

您设置的DEFAULT_WIDTHDEFAULT_HEIGHT用于整个框架,包括边框,窗口标题,图标等。它不是绘图画布本身的大小。因此,如果您在200x200画布中绘制某些内容,则预计它不一定适合包含该画布的200x200窗口。