添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm trying to add a constructor to the javax.swing.ImageIcon . It shall resolve the directory structure to be able to access the ImageIcon class like a image map.

What I'm trying to do is:

public class CPImageIcon extends ImageIcon {
    public CPImageIcon(String name) {
        super(this.getClass().getResource("/desktopapplication1/resources/" + name), "description");

but this leads to:

warning: [options] bootstrap class path not set in conjunction with -source 1.7
I:\DesktopApplication1\src\desktopapplication1\CPImageIcon.java:18: error: cannot reference this before supertype constructor has been called
        super(this.getClass().getResource("/desktopapplication1/resources/" + name),"");

If I try to super other constructors it works.

Do you really need to extend ImageIcon? Could you not just use a factory method to construct an instance of ImageIcon directly? – Andy Turner May 28, 2020 at 10:46

super constructor must be the first call in subclasses constructors. If ommitted it will call automatically to default constructor super().

this represent the current instance, and can't be used before calling super.

You could use the following approach, commented or uncommented:

import javax.swing.*;
public class CPImageIcon extends ImageIcon {
    public CPImageIcon(String name) {
        super(CPImageIcon.class.getResource("/desktopapplication1/resources/" + name), "description");
//        super(Thread.currentThread().getContextClassLoader().getResource("/desktopapplication1/resources/" + name), "description");
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.