繁体   English   中英

从外部 jpanel class 移动 JFrame

[英]Move JFrame from external jpanel class

我试图通过从外部 jpanel class 触发的事件在 window 上移动 jframe,我的代码在下面,但没有实现这一点。 相反,面板是移动的面板。

我在这里做错了什么? 我一般是新编程。

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

setLocation() 设置您的 JPanel 的位置(因为您的 class 扩展了 JPanel)。 如果您有对 JFrame 的引用,则可以在该 object 上调用 setLocation 方法。

frame.setLocation(x, y);

如果您没有参考资料,那么您可以关注这篇通过 SwingUtilities 访问框架的帖子

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM