How can I properly center a JPanel ( FIXED SIZE ) inside a JFrame?

前端 未结 6 2046
死守一世寂寞
死守一世寂寞 2020-12-03 03:27

Hi all! I\'m trying to solve an -apparently- simple problem, but I cannot fix it. I\'m working on a sample application with Java/Swing libraries; I have a JFrame and a JPan

6条回答
  •  时光取名叫无心
    2020-12-03 03:55

    You can do this. I had to make a chess game, and I wanted the chess piece piece to always go in the center of a cell which was a JlayeredPane:

    private void formMouseReleased(java.awt.event.MouseEvent evt) {
        // TODO add your handling code here:
        if (jl != null)
        {
            jl.setLocation(evt.getX()+10, evt.getY()+10);
            Component com = findComponentAt(evt.getPoint());
            if (com instanceof JPanel)
            {
                // System.out.println("Yes, it's a jpanel");
                ((JPanel)com).add(jl);
                ((JPanel)com).validate();
            }
        }
    }
    

提交回复
热议问题