Suppose I've the following code for an Icon
called SquareIcon
:
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class SquareIcon implements Icon
{
private int size;
private Color color;
public SquareIcon(int size, Color color) {
this.size = size;
this.color = color;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g;
// Rectangle2D.Double implements Shape
// The Double class defines a rectangle specified in double coordinates.
Rectangle2D.Double figure = new Rectangle2D.Double(x, y, size, size);
g2d.setColor(color);
// Fills the interior of a Shape using the settings of the Graphics2D context
g2d.fill(figure);
}
@Override
public int getIconWidth() {
return size;
}
@Override
public int getIconHeight() {
return size;
}
}
toghether with a corresponding test class called SquareIconTest
:
public class SquareIconTest {
public static void main(String[] args) {
SquareIcon icon = new SquareIcon(50, Color.BLUE);
JOptionPane.showMessageDialog(
null,
"Blue SquareIcon",
"SquareIcon Test",
JOptionPane.INFORMATION_MESSAGE,
icon
);
}
}
How does the Rectangle2D.Double
knows it should be displayed inside the JOptionPane
? I see that the x
and y
variables must be the position inside this pane, but where do the rectangle gets the other information?
I've read the JavaDoc, and it says that g2d.fill()
fills the interior of a Shape
, i.e. sets its color? This doesn't provide information about the pane?