【问题标题】:Extended JLabel class not showing in layered pane [closed]扩展的 JLabel 类未显示在分层窗格中[关闭]
【发布时间】: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


【解决方案1】:

作为@Hovercraft comments,问题可能出在其他地方——图像加载失败或组件边界错误。 minimal example 将允许您研究隔离问题并使用结果来完善您的完整程序。

从这个example开始,我将这些行添加到LayerPanel构造函数中得到下图

this.setLayout(new FlowLayout(FlowLayout.RIGHT));
this.add(new JLabel(String.valueOf(n)), JLabel.RIGHT_ALIGNMENT);

这利用面板的layout 将标签定位在右上角;相比之下,paintComponent() 的实现在左下角的固定位置绘制。

接下来,认真检查扩展 JLabel 的必要性。如图herehereJLabel本身可以控制文字和图标的相对位置;而父 JComponent 可以存储任意的组件特定属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多