java - 如何在Java中调整绘制的椭圆形的大小?

标签 java swing

我需要调整 Java 中绘制的椭圆形的大小,我为其创建了以下代码:

FrameView.java

package tutorial;

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

public class FrameView{
    public static void main(String args[]){
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        BallCreation c = new BallCreation();
        f.add(c);
        f.setSize(500, 500);
        f.setVisible(true);
    }
}

BallCreation.java

package tutorial;

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

public class BallCreation extends JPanel{
    private static final long serialVersionUID = 1L;
    private int height = 10;
    private int width = 10;
    private JPanel panel;
    private JButton button1;

    public BallCreation(){
        panel = new JPanel();

        button1 = new JButton("Click");
        add(button1);

        button1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){
                height = height + 2;
                width = width + 2;
            }
        });


    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        this.setBackground(Color.WHITE);

        g.setColor(Color.GREEN);
        g.fillOval(10, 10, width, height);
    }
}

问题是它不起作用,我不知道如何使椭圆刷新到新的大小。我认为它应该可以工作,但由于某种原因,按钮无法解析 paintComponent 上的新高度和宽度。

最佳答案

只需在 actionPerformed 方法末尾添加一个 repaint() ,否则您将看不到更改(除非您最小化然后恢复窗口,例如,强制重新绘制该区域)。

button1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){
                height = height + 2;
                width = width + 2;
                repaint();
            }
        });

关于java - 如何在Java中调整绘制的椭圆形的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39747521/

相关文章:

java - 如何使用 spring-kafka 暂停和恢复 @KafkaListener

java - session.delete 和使用 HQL 删除有什么区别

java - 无法使用 Spring RestTemplate 调用 Salesforce API

java - 如何从 JTextArea 中提取具有给定字体的文本的单词和换行信息

Java:取消按钮不会关闭 JFrame 的窗口

java - Log4J 动态配置

java - 桌面应用程序的 Swing 与 JavaFx

java - swing JTree、JTable 或 JList 中的 Activity 元素

java - 在 Java 应用程序 (Swing) 中刷新/重新加载图像

java - Android 中的自定义最大 asyncTasks