0

I'm trying to move around jframe on the window through an event triggered from an external jpanel class, my code is below, but the doesn't achieve this. Instead the panel is the one that's moving around.

What am I doing wrong here? I am new programming in general.

package casuls_app;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Titlebar extends JPanel  {
    public Titlebar() {
        
        btnClose =new JButton("X");
        btnClose.setFocusable(false);
        btnClose.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                closeButtonPressed(e);
                }
            }
        );
        
        controlBox =new JPanel(new GridLayout(1,1));
        controlBox.setPreferredSize(new Dimension(150,40));

        controlBox.add(btnClose);
        controlBox.setBackground(new Color(255,255,255));
        
        setLayout(new BorderLayout());
        add(controlBox,BorderLayout.EAST);
        setPreferredSize(new Dimension(0,40));
        setBackground(new Color(60, 173, 205));
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                mousePressedOnTitlebar(e);
            }
        }
        );
        
        addMouseMotionListener(new MouseAdapter() {
            public void mouseDragged(MouseEvent e) {
                mouseDraggedOnTitlebar(e);
            }
        }
        );
    }
    
    private void mousePressedOnTitlebar(MouseEvent e) {
        posX= e.getX();
        posY=e.getY();
    }
    
    private void mouseDraggedOnTitlebar(MouseEvent e) {
        setLocation(e.getXOnScreen() -posX, e.getYOnScreen() -posY);
    }
    
    private void closeButtonPressed(ActionEvent e){
        System.exit(0);
    }
    
    
    //Variables declaration
    private int posX,posY;
    private JButton btnClose;
    private JPanel controlBox;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Joel
  • 91
  • 7

1 Answers1

2

setLocation() sets the location of your JPanel (because your class extends JPanel). If you have a reference to the JFrame, you can call the setLocation method on that object.

frame.setLocation(x, y);

If you don't have the reference, then you can follow this post which accesses the frame via SwingUtilities:

JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);