有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

简单框架和图形的java帮助

作为家庭作业,我试图创建一个“自定义按钮”,它有一个框架,在这个框架中,我画了两个三角形,在上面画了一个正方形。它应该给用户一个按下按钮的效果。所以对于初学者,我尝试设置开始的图形,绘制两个三角形和一个正方形。我遇到的问题是,虽然我将帧设置为200,200,并且我绘制的三角形我认为是帧大小的正确端点,但当我运行程序时,我必须扩展窗口以使整个艺术品(我的“自定义按钮”)可见。这正常吗?谢谢

代码:

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) 个答案

  1. # 1 楼答案

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

  2. # 2 楼答案

    尝试添加

    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文档:)

    Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.

    你应该得到类似于:

    enter image description here