温馨提示×

java怎么设置窗体不可移动

小亿
109
2023-11-13 10:02:43
栏目: 编程语言

在Java中,可以通过设置窗体的setUndecorated方法来设置窗体不可移动。具体步骤如下:

  1. 创建一个JFrame对象,用于表示窗体:
JFrame frame = new JFrame();
  1. 使用setUndecorated方法将窗体设置为无装饰的窗体:
frame.setUndecorated(true);
  1. 在窗体的MouseMotionListener中添加鼠标监听事件,监听鼠标的拖动操作:
frame.addMouseMotionListener(new MouseMotionAdapter() {
    public void mouseDragged(MouseEvent e) {
        // Do nothing
    }
});
  1. 运行程序,窗体将无法移动。

完整代码示例:

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

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setUndecorated(true);
        frame.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                // Do nothing
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}

0