【发布时间】:2021-10-09 18:55:03
【问题描述】:
在我的函数create() 中,我试图实例化一个note 类的对象,它是JLabel 的扩展。然后我想将此对象添加到深度为 1 的JLayeredPane(称为lp),以便将其显示在我的背景图像上方。实例化运行良好,但未显示 newNote 对象。
这里是note类的代码:
import javax.swing.ImageIcon;
import javax.swing.JLabel;
//This class will be used to instanciate new notes for the user
public class note extends JLabel{
final static ImageIcon image = new ImageIcon(note.class.getResource("semibreve1-removebg-preview.png"));
//attributes
private String length;
private String note1;
private String code;
private String val;
//Constructor
note(String myLength, String myNote){
super("",image,LEADING);
this.length = myLength;
this.note1 = myNote;
generateCode();
//System.out.println("note creation confirmed: "+code);
}
//Getters and setters below
这是我的创建函数的代码。
public void create(l,n){
note newNote = new note(l,n);
noteObjects.add(newNote);
newNote.setBounds(0,0,newNote.image.getIconWidth(),newNote.image.getIconHeight());
newNote.setSize(newNote.getPreferredSize());
lp.add(newNote,1);
}
感谢您的宝贵时间。
【问题讨论】:
-
如果您没有很快得到一个体面的答案,请考虑创建并发布一个有效的minimal reproducible example 并附上您的问题。这不是您的整个程序,而是为我们编译和运行的一个较小的新程序,它直接为我们演示您的问题,但又足够小,可以完整地发布您的问题。
-
您确认
image不为空吗? -
它是否显示在常规的 JPanel 上?使用布局管理器时首先获取基本逻辑。然后让它工作的 JLayeredPane 涉及更多,因为您需要手动管理大小/位置。
-
一切正常,只需要使用
this.setOpaque(true);将不透明度设置为true
标签: java swing user-interface jlabel jlayeredpane