gpt4 book ai didi

java - `Rectangle2D.Double` 如何知道它应该在对 `JOptionPane` 的调用中显示在 `paintIcon()` 内?

转载 作者:行者123 更新时间:2023-11-30 03:11:00 26 4
gpt4 key购买 nike

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

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 变量必须是该 Pane 内的位置,但是矩形从哪里获取其他信息?

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

最佳答案

The Graphics object tells the rectangle that it should be displayed inside the JOptionPane?

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

关于java - `Rectangle2D.Double` 如何知道它应该在对 `JOptionPane` 的调用中显示在 `paintIcon()` 内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33646488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com