【问题标题】:How does the `Rectangle2D.Double` knows it should be displayed inside the `JOptionPane` in this call to `paintIcon()`?在对 `paintIcon()` 的调用中,`Rectangle2D.Double` 如何知道它应该显示在 `JOptionPane` 中?
【发布时间】:2015-11-11 08:10:55
【问题描述】:

假设我有一个名为IconSquareIcon 的以下代码:

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 中?我看到xy 变量必须是这个窗格内的位置,但是矩形从哪里获取其他信息?

我读过JavaDoc,它说g2d.fill() 填充了Shape 的内部,即设置它的颜色?这不提供有关窗格的信息?

【问题讨论】:

  • 因为您将icon 作为参数传递给showMessageDialog 方法?
  • 你的图标类中的 Rectangle2d.Double 不知道它会在哪里显示,JOptionPane 知道它应该使用你的图标类(所以这样循环)
  • Graphics 上下文已被翻译到被绘制组件的上下文中。
  • @EmersonCod,是的,但是“paintIcon()”方法不返回这个矩形?
  • @NicolasLykkeIversen no - paint 方法有 void 所以它什么也不返回。它获取要绘制的 Graphics 对象。这(简短地说)取自 JOptionPane,因此图标出现在那里

标签: java swing icons paint


【解决方案1】:

Graphics 对象告诉矩形它应该显示在JOptionPane 内?

没有。如Painting in AWT and Swing 所述,系统告诉图标自己绘制。当JOptionPane 可见时,必须绘制其内容。最终,在包含Icon 的选项窗格标签上调用paintComponent()。传入paintIcon() 的几何图形由封闭容器的布局和插图定义。在这个相关的example 中,注意setHorizontalAlignment() 如何定义标签中的图标和文本之间的关系。查看事件链的一种简单方法是在对fill() 的调用上设置断点并在调试器中检查调用链。您的示例直接添加了Icon JOptionPane。作为一个实验,尝试创建一个带有文本/图标的Label 并将其添加到JOptionPane

【讨论】:

    猜你喜欢
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 2019-12-01
    • 2020-02-16
    相关资源
    最近更新 更多