使用图标和 myIcon

Using Icon and myIcon

我正在练习使用 Icon 和 myIcon,但收到一条错误消息,指出 myIcon 必须在其自己的文件中定义。我很确定我在代码中定义了它,但我很困惑我做错了什么。

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class TestIcon {
    public static void main(String[] args) {
        myIcon icn = new myIcon(40,50);
        JOptionPane.showMessageDialog(null, "Hello World!", "Message", JOptionPane.INFORMATION_MESSAGE, icn);
    }
}

public class myIcon implements Icon{
    private int width;
    private int height;

    public myIcon(int width, int height) {
        this.width=width;
        this.height=height;
    }
    public int getIconWidth(){
        return width;
    }
    public int getIconHeight(){
        return height;
    }
    public void paintIcon(Component c, Graphics g, int x, int y){
        Graphics2D g2 = (Graphics2D) g;
        Ellipse2D.Double ellipse = new Ellipse2D.Double(x,y,width, height);

        g2.setColor(Color.RED);
        g2.fill(ellipse);
    }
 }

要么将 myIcon 移动到它自己的文件中,要么使 myIcon 成为 TestIcon 的内部 class,例如...

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.Icon;
import javax.swing.JOptionPane;

public class TestIcon {

    public static void main(String[] args) {
        myIcon icn = new myIcon(40, 50);
        JOptionPane.showMessageDialog(null, "Hello World!", "Message", JOptionPane.INFORMATION_MESSAGE, icn);
    }

    public static class myIcon implements Icon {

        private int width;
        private int height;

        public myIcon(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public int getIconWidth() {
            return width;   
        }

        public int getIconHeight() {
            return height;
        }

        public void paintIcon(Component c, Graphics g, int x, int y) {
            Graphics2D g2 = (Graphics2D) g;
            Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, width, height);

            g2.setColor(Color.RED);
            g2.fill(ellipse);
        }
    }

}

A​​ inner class 施加了一些限制,所以取决于你想做什么,将取决于你做什么。