我想制作一個標簽并將其移動到螢屏上。我試圖找到一些視頻和其他資源以找到如何做到這一點,但無法很好地理解它們,或者他們使用了我從未聽說過的東西。所以我撰寫了這段代碼(框架擴展了 JFrame 并實作了 MouseListener):
這是主類:
public class Main {
public static void main(String[] args) {
new Frame();
}
}
這是帶有代碼的類:
public class Frame extends JFrame implements MouseListener{
JLabel label;
Frame() {
label = new JLabel();
label.setBounds(800, 200, 200, 200);
label.setBackground(Color.RED);
label.setOpaque(true);
label.addMouseListener(this);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(1200, 700);
this.setLayout(null);
this.add(label);
this.setVisible(true);
this.setLocationRelativeTo(null);
}
@Override
public void mouseReleased(MouseEvent e) {
Point x = e.getPoint();
label.setLocation(x);
System.out.println(x);
}
當我嘗試移動標簽時,標簽會移動,但不是在我想要的位置。只有有時,標簽會朝我想要的方向移動,但大多數時候,它會朝任意隨機方向移動。即使我只是點擊,它也會移動。但是,即使標簽向我想要的方向移動,它也會在該方向上隨機長度。
uj5u.com熱心網友回復:
您可以使用 aMouseListener來跟蹤何時按下滑鼠并獲取標簽的坐標,并使用 aMouseMotionAdapter來跟蹤滑鼠何時移動(或拖動)以幫助您設定標簽的新位置。
更新:
要添加有關其作業原理的更多資訊,e.getLocationOnScreen().x請根據計算機螢屏回傳滑鼠按下的 X 坐標,同時label.getX()根據已添加到的 Java Swing 容器回傳標簽的 X 坐標;在這種情況下,就是JFrame. 因此,必須從前一個值中減去該值才能獲得螢屏上標簽的實際 X 坐標。同樣適用于 Y 坐標。獲得兩個坐標后,您可以使用該label.setLocation()方法更改標簽的位置,從而在螢屏上移動標簽。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LabelDragExample extends JFrame {
JLabel label;
int x, y;
public LabelDragExample() {
label = new JLabel();
label.setBounds(800, 200, 200, 200);
label.setBackground(Color.RED);
label.setOpaque(true);
label.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
x = e.getLocationOnScreen().x - label.getX();
y = e.getLocationOnScreen().y - label.getY();
}
});
label.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
label.setLocation(e.getLocationOnScreen().x - x, e.getLocationOnScreen().y - y);
x = e.getLocationOnScreen().x - label.getX();
y = e.getLocationOnScreen().y - label.getY();
}
});
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(1200, 700);
this.setLayout(null);
this.setVisible(true);
this.add(label);
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
new LabelDragExample();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411468.html
標籤:
