我正在制作一个自定义JFrame
。我已经有了这个布局,并且它工作得很好:
框架未装饰,但我希望能够移动它。我希望我的自定义面板成为此操作的移动 handle ,因此我所做的就是向其中添加一个 MouseMotionListener
。 mouseDragged 函数如下所示:
@Override
public void mouseDragged(MouseEvent e) {
parent.setBounds(e.getX(), e.getY(), parent.getWidth(), parent.getHeight());
}
parent
字段在构造函数中设置,并且是最终的。
当我尝试用面板拖动框架时,它可以工作,但不太正确。框架在屏幕上的两个位置之间不断闪烁。我可以移动框架,但看起来很糟糕。当我不拖动框架时,它不会闪烁。这两个位置是相对于彼此的,因此如果移动框架,另一个框架也会随之移动(但与另一个框架的距离不同)。另一个问题是框架不能很好地随着鼠标移动。因此,如果您将框架在 x 方向上移动 100 个像素,则框架在同一方向上移动的像素会更少。
如何为 JFrame 制作移动夹点而不发生这种情况(以及实际上是什么导致它这样做)?
如果需要更多代码,请告诉我。
最佳答案
您还需要提供一个mousePressed
来获取点击的初始点。然后使用该点进行一些计算。
尝试这样的操作,其中 pX
和 pY
是类字段(并假设在面板构造函数中添加了监听器
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// Get x,y and store them
pX = me.getX();
pY = me.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent me) {
parent.setLocation(parent.getLocation().x + me.getX() - pX,
parent.getLocation().y + me.getY() - pY);
}
});
<小时/>
这是一个完整的示例
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class UndecoratedExample {
private JFrame frame = new JFrame();
class MainPanel extends JPanel {
public MainPanel() {
setBackground(Color.gray);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
class BorderPanel extends JPanel {
private JLabel label;
int pX, pY;
public BorderPanel() {
label = new JLabel(" X ");
label.setOpaque(true);
label.setBackground(Color.RED);
label.setForeground(Color.WHITE);
setBackground(Color.black);
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(label);
label.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
System.exit(0);
}
});
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// Get x,y and store them
pX = me.getX();
pY = me.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent me) {
frame.setLocation(frame.getLocation().x + me.getX() - pX,
frame.getLocation().y + me.getY() - pY);
}
});
}
}
class OutsidePanel extends JPanel {
public OutsidePanel() {
setLayout(new BorderLayout());
add(new MainPanel(), BorderLayout.CENTER);
add(new BorderPanel(), BorderLayout.PAGE_START);
setBorder(new LineBorder(Color.BLACK, 5));
}
}
private void createAnsShowGui() {
frame.setUndecorated(true);
frame.add(new OutsidePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new UndecoratedExample().createAnsShowGui();
}
});
}
}
关于java - 使用自定义握把/ handle 杆移动 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23035591/