可見JComponents我試圖代碼,主要是用於以示範一個簡單的Java應用程序,但它不會出於某種原因。它的主要功能是基本跟蹤鼠標的移動,並在鼠標所在的位置繪製一個框。我一直在研究一些代碼,這就是我所擁有的。難道我做錯了什麼?圖紙上的MouseEvent
這是主類
package peter;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Frame extends JPanel implements MouseMotionListener {
private final static JFrame window = new JFrame();
public Frame(){
addMouseMotionListener(this);
setPreferredSize(new Dimension(450, 450));
setBackground(Color.GREEN);
}
private static int mouseX;
private static int mouseY;
public static void main(String[] args){
//Create and set up the window.
JFrame frame = new JFrame("MouseMotionEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new Frame();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
@Override
public void mouseDragged(MouseEvent e)
{
;
}
@Override
public void mouseMoved(MouseEvent e)
{
JComponent P = new Paintings();
window.add(P);
System.out.println("Mouse moved");
}
public static int getMouseY()
{
return MouseInfo.getPointerInfo().getLocation().y;
}
public static int getMouseX()
{
return MouseInfo.getPointerInfo().getLocation().x;
}
public static Rectangle rectOnMouse()
{
Rectangle rect = new Rectangle(getMouseX(), getMouseY(), 10,10);
return rect;
}
}
這是繪畫類
package peter;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class Paintings extends JComponent{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.draw(Frame.rectOnMouse());
}
}
你的 'getMouseX()' 將返回 'Y'。 – leeor
我更新了代碼以解決此問題。感謝您的輸入 –
在您做出大量不正確的假設時閱讀教程。對於你重複創作和添加繪畫對象是錯誤的。爲什麼要重複組件? –