[英]Mouse - Motion Listener not working
我是這里的新手。 我在這里有一個代碼,希望將JLabel的文本更改為移動鼠標的位置。 這是我的代碼。
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Draw extends JFrame{
int x;
int y;
String positions = "Positions: " + x + ", " + y;
JLabel positionsOnFrame = new JLabel(positions);
public class AL implements MouseMotionListener {
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
}
public void mouseDragged(MouseEvent e) {
positions += " dragged.";
}
}
//Constructor
public Draw() {
setTitle("Title");
setBackground(Color.BLACK);
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
addMouseMotionListener(new AL());
add(positionsOnFrame);
setVisible(true);
}
public static void main(String[] args) {
new Draw();
}
}
副作用:即使我從構造函數中將顏色設置為黑色,JFrame也不會變黑。
有解決鼠標問題的方法嗎? 什么都沒發生! 值僅設置為0! (我尚未初始化它們,它們只是自動設置為0!)。 幫助將不勝感激!
這應該工作
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
positionsOnFrame.setText("Positions: " + x +", " + y);
System.out.println(x);
}
對於背景色,這應該起作用。
getContentPane().setBackground(Color.BLACK);
每次x
和y
更改時,字符串positions
都不會更改。 該值將與最初分配x
和y
時的值相同。
例如
String s = "hello";
String t = s;
System.out.println(t);
s = "bye";
System.out.println(t);
會兩次hello
首先,未初始化的整數(例如x和y)的默認值為零。 但是依靠它不是一個好習慣。 最好即使它們仍然為零,也要顯式初始化它們的值。
接下來,實際上將調用mouseMoved()回調。 但這不是在更新“ positionsOnFrame”標簽的文本,而是在更新x和y坐標。 僅僅因為您使用字符串(位置)創建了標簽,並不意味着標簽的文本將在更改字符串時自動更改。 您必須相應地更改標簽的文本。 因此,添加positionsOnFrame.setText(“ Positions:” + x +“,” + y); 在mouseMoved()回調內部將修復該部分。
最后,直接更改框架內容窗格的顏色,而不是直接更改框架的顏色:getContentPane()。setBackground(Color.BLACK);
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.