简体   繁体   English

在Java中按下按钮时如何绘制正方形

[英]How to draw a square when a button is pressed in java

I am writing a java program where you input a length and you input a width of a rectangle and it outputs the perimeter and area. 我正在编写一个Java程序,在其中输入长度,然后输入矩形的宽度,并输出周长和面积。 But now, I want to draw the figure as well. 但是现在,我也想得出这个数字。 But I don't know how to draw it when the button is pressed. 但是我不知道如何在按下按钮时绘制它。 Should it look like this?: 应该是这样吗?:

public void paintComponent(Graphics g) {
    paintComponent(g);
    g.setColor(Color.blue);
    g.drawRect(10, 10, 80, 30);      
}

public void actionPerformed(ActionEvent e) {
    paintComponent();
}

Because when I do that it gives me an error saying: 因为当我这样做时,它给我一个错误,说:

method paintComponent in class Rectangles cannot be applied to given types;
required: Graphics
found: no arguments

So I don't really know what to do. 所以我真的不知道该怎么办。

No, you shouldn't call paintComponent directly. 不,您不应该直接调用paintComponent That method will be called automatically anyway, so the square would be drawn before you click. 无论如何,该方法都会自动调用,因此将在单击之前绘制正方形。

You could use a boolean flag to indicate that you clicked the button and call repaint() to post a repaint request: 您可以使用布尔标志来表示您单击了按钮,然后调用repaint()来发布重新绘制请求:

boolean clicked = false;

public void paintComponent(Graphics g) {
    if (clicked) {
        g.setColor(Color.blue);
        g.drawRect(10, 10, 80, 30);
    }
}

public void actionPerformed(ActionEvent e){
    clicked = true;
    repaint();
}

Moreover, never let a method call itself with exactly the same parameters. 此外, 切勿让方法使用完全相同的参数来调用自身。 This snipped 这个被抢了

public void paintComponent(Graphics g) {
    paintComponent(g);

will call the same function infinitely often (or until the stack is full). 将无限次地(或直到堆栈已满)调用同一函数。

I think you saw the following somewhere: 我认为您在某处看到以下内容:

public void paintComponent(Graphics g) {
    super.paintComponent(g);

That is ok, it will call the paint method of the super class. 没关系,它将调用超类的paint方法。 It probably doesn't do anything, so leaving it out shouldn't harm (but neither does keeping it). 它可能什么也没做,因此将其遗弃也不会造成伤害(但也不会保留它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM