Java – place the component on the glass pane

I have a subclass of jlabel that forms a component of my GUI I have implemented the ability to drag and drop components from one container to another without any visual effects I want this jlabel to follow the cursor during dragging from one container to another I think I can create a glass window and draw it there However, even if I add a component to the pane, set the component to visible, set the pane to visible, and set the pane to opaque, I still can't see the component I know how components work because I can add them to the content pane and display them

How do I add components to a glass pane?

Finally, I think of how to make simple examples work Thank you, @ AKF I was able to adapt this solution to my original problem, allowing me to delete about 60 lines of Java2D code manually rendered in jlabel

package test;

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

public class MainFrame extends JFrame {

    /**
     * @param args
     */
    public static void main(String[] args) {
        MainFrame mf = new MainFrame();
        mf.setSize(400,400);
        mf.setLocationRelativeTo(null);
        mf.setDefaultCloSEOperation(DISPOSE_ON_CLOSE);
        mf.setGlassPane(new JPanel());

        JLabel l = new JLabel();
        l.setText("Hello");
        l.setBorder(new LineBorder(Color.BLACK,1));
        l.setBounds(10,10,50,20);
        l.setBackground(Color.RED);
        l.setOpaque(true);
        l.setPreferredSize(l.getSize());

        //mf.add(l);
        ((JPanel)mf.getGlassPane()).add(l);
        mf.getGlassPane().setVisible(true);

        mf.setVisible(true);
    }
}

Solution

In addition to the pointer of the layerpane example already provided, the problem of the original code revolves around the setting of the preferred size of the label You set it before the size of jlabel, so your

l.setPreferredSize(l.getSize());

Is invalid On the other hand, if you call after calling setbounds, you will see the desired results With this in mind, please reorder:

l.setPreferredSize(l.getSize());
l.setBounds(10,20);

It looks like this:

l.setBounds(10,20);
l.setPreferredSize(l.getSize());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>