Put JLabel in front of Graphics 2D Rectangle in JPanel

匆匆过客 提交于 2019-12-13 04:01:50

问题


Is there any way to put the JLabel in front of the rectangle? Currently, the JLabel is underneath the rectangle.

Here is my relevant code:

public class MainMenu_South extends JPanel {
        MainMenu_BlueJay t; 
        JLabel start=new JLabel("START");

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.blue);
        g2d.drawRect(0, 30, 900, 30); 
        g2d.fillRect(0, 30, 900, 30);
    }

    public MainMenu_South(MainMenu_BlueJay t){

        setLayout(null);
        this.t=t;
        setBackground(Color.white);

        start.setForeground(Color.red);
        start.setFont(new Font("Arial", Font.BOLD, 16));

        add(start);
        start.setBounds(100, 10, 100, 50);
        start.addMouseListener(ml);
    }

    MouseListener ml=new MouseListener() {

        @Override
        public void mouseEntered(MouseEvent e) {//hover
           start.setForeground(Color.white);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            start.setForeground(Color.red);
        }
    };

}

回答1:


  1. for better help sooner post an MCVE

  2. use paintComponent() for Swing JComponents instead of paint()

  3. there isn't reason to use NullLayout, use LayoutManager,

  4. override getPreferredSize for JPanel, then JFrame.pack() will generate expected Dimension on the screen

  5. JLabel is transparent, you have to setOpaque if you to want to dispaly Color as Backgroung in Jlabel

  6. you have to use repaint(last code line) for MouseEvents and Color for JLabel, override MouseAdapter

  7. miss any, no idea if you would need use transparency or tranclucency, or remove the JLabel



来源:https://stackoverflow.com/questions/21076693/put-jlabel-in-front-of-graphics-2d-rectangle-in-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!