【发布时间】:2015-11-11 08:10:55
【问题描述】:
假设我有一个名为Icon 的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;
}
}
连同一个名为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
);
}
}
Rectangle2D.Double 如何知道它应该显示在 JOptionPane 中?我看到x 和y 变量必须是这个窗格内的位置,但是矩形从哪里获取其他信息?
我读过JavaDoc,它说g2d.fill() 填充了Shape 的内部,即设置它的颜色?这不提供有关窗格的信息?
【问题讨论】:
-
因为您将
icon作为参数传递给showMessageDialog方法? -
你的图标类中的 Rectangle2d.Double 不知道它会在哪里显示,JOptionPane 知道它应该使用你的图标类(所以这样循环)
-
Graphics上下文已被翻译到被绘制组件的上下文中。 -
@EmersonCod,是的,但是“paintIcon()”方法不返回这个矩形?
-
@NicolasLykkeIversen no - paint 方法有
void所以它什么也不返回。它获取要绘制的 Graphics 对象。这(简短地说)取自 JOptionPane,因此图标出现在那里