【问题标题】:Put JLabel in front of Graphics 2D Rectangle in JPanel将 JLabel 放在 JPanel 中 Graphics 2D Rectangle 的前面
【发布时间】:2014-01-12 15:47:10
【问题描述】:

有什么办法可以把 JLabel 放在矩形前面吗?目前,JLabel 位于矩形下方。

这是我的相关代码:

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);
        }
    };

}

【问题讨论】:

  • 阅读swing tag wiki中引用的绘画文章:-)
  • 你知道为什么这个问题没有得到回答

标签: java swing panel graphics2d


【解决方案1】:
  1. 如需更好的帮助,请尽快发帖MCVE

  2. 对 Swing JComponents 使用 paintComponent() 而不是 paint()

  3. 没有理由使用NullLayout,使用LayoutManager

  4. getPreferredSize 覆盖为JPanel,然后JFrame.pack() 将在屏幕上生成预期的Dimension

  5. JLabel是透明的,如果你想在Jlabel中显示ColorBackgroung,你必须setOpaque

  6. 对于MouseEvents,您必须使用repaint(last code line),对于JLabel,必须使用Color,覆盖MouseAdapter

  7. 错过任何一个,不知道您是否需要使用透明或半透明,或者删除 JLabel

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2012-04-07
    • 1970-01-01
    相关资源
    最近更新 更多