so I have this project that I'm doing, which draws a circle and a square, and resizes them through buttons. Everything works great, however what I must do is put the circle inside the square, so that the circle is inscribed, and I can't seem to figure out how to put both swing elements on top of each other.
Here's a picture of how it currently is:
And here's a photoshop version of how it should look like:
Here's my Circle class:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
public class Picture extends Canvas implements VetoableChangeListener, PropertyChangeListener {
private final int SIZE = 100;
private int radius = 1;
public Picture() {
setSize(SIZE,SIZE);
}
public void vetoableChange(PropertyChangeEvent pce) throws PropertyVetoException {
if ((pce.getPropertyName()).equals("value")) {
int v = (Integer)pce.getNewValue();
if ((v <=0)||(v > SIZE/2))
throw new PropertyVetoException ("Value out of bounds!", pce);
}
}
public void propertyChange(PropertyChangeEvent pce) {
if ((pce.getPropertyName()).equals("value")) {
setRadius((Integer)pce.getNewValue());
repaint();
}
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getRadius() {
return this.radius;
}
public void paint (Graphics g) {
Dimension d = getSize();
g.setColor(Color.GREEN);
g.fillOval(d.width/2 - radius, d.height/2 - radius, radius*2, radius*2);
}
}
And here's my Square class, which is similar:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
public class Square extends Canvas implements VetoableChangeListener, PropertyChangeListener {
private final int SIZE = 100;
private int side = 1;
public Square() {
setSize(SIZE,SIZE);
}
public void vetoableChange(PropertyChangeEvent pce) throws PropertyVetoException {
if ((pce.getPropertyName()).equals("value")) {
int v = (Integer)pce.getNewValue();
if ((v <=0)||(v > SIZE/2))
throw new PropertyVetoException ("Value out of bounds!", pce);
}
}
public void propertyChange(PropertyChangeEvent pce) {
if ((pce.getPropertyName()).equals("value")) {
setSide((Integer)pce.getNewValue());
repaint();
}
}
public void setSide(int side) {
this.side = side;
}
public int getSide() {
return this.side;
}
public void paint (Graphics g) {
Dimension d = getSize();
g.setColor(Color.BLUE);
g.drawRect(d.width/2 - side, d.height/2 - side, side*2, side*2);
}
}
I've added both of them to the palette. Would you please explain to me how to put those both elements on top of each other, I'm new to Swing and JavaBeans.
Thanks in advance!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…