Tom Tom - 2 months ago 12
Java Question

How to resize a drawn oval in Java?

I need to resize a drawn oval in Java, I created this code for it:

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);
}
}


The problem is is that it isn't working, I am not sure how I can make the oval refresh to its new size. I think it should be working, but for some reason the button doesn't parse the new height and width on to the
paintComponent
.

Answer

Just add a repaint() at the end of your actionPerformed method , or you won't see the change (unless you minimize then restore your window for instance, to force a repaint of the area).

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