更改Dialog位置Java代码_Java Swing - 如何移动JFrame并更新JDialog位置

该代码段展示了一个Java应用程序,其中包含一个JFrame和一个JDialog。当JFrame移动时,JDialog会随之移动,实现了窗口组件的同步定位。主要涉及到Java AWT和Swing库中的窗口事件监听和位置调整。
摘要由CSDN通过智能技术生成

import java.awt.Point;

import java.awt.event.ComponentAdapter;

import java.awt.event.ComponentEvent;

import javax.swing.JDialog;

import javax.swing.JFrame;

public class Main {

public static void main(String[] args) {

JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JDialog dialog = new JDialog(frame, false);

dialog.setSize(200, 50);

frame.addComponentListener(new ComponentAdapter() {

Point lastLocation;

@Override

public void componentMoved(ComponentEvent e) {

if (lastLocation == null && frame.isVisible()) {

lastLocation = frame.getLocation();

} else {

Point newLocation = frame.getLocation();

int dx = newLocation.x - lastLocation.x;

int dy = newLocation.y - lastLocation.y;

dialog.setLocation(dialog.getX() + dx, dialog.getY() + dy);

lastLocation = newLocation;

}

}

});

frame.setSize(400, 200);

frame.setVisible(true);

dialog.setLocationRelativeTo(frame);

dialog.setVisible(true);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值