如何让鼠标处理程序在DrawPanel中工作,以便制作一个显示当前鼠标位置的标签



我正试图将MouseHandler添加到我的DrawPanel类中,以最终获得一个更新鼠标位置的状态标签,但在使用print语句时,它似乎根本没有注册任何鼠标输入。

private class DrawPanel extends JPanel {
public DrawPanel() {
JPanel mousePanel = new JPanel();
this.add(mousePanel);
MouseHandler handler = new MouseHandler();
mousePanel.addMouseListener(handler);
mousePanel.addMouseMotionListener(handler);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
}
private class MouseHandler extends MouseAdapter implements MouseMotionListener {
@Override
public void mousePressed(MouseEvent event) {
System.out.print("Pressed");
}
@Override
public void mouseReleased(MouseEvent event) {
System.out.print("Released"); 
}
@Override
public void mouseDragged(MouseEvent event) {
System.out.print("Dragged"); 
//lblStatus.setText(String.format("(%d,%d)",event.getX(),event.getY()));
}
@Override
public void mouseMoved(MouseEvent event) {
System.out.print("Moved");
//System.out.print("("+event.getX()+","+event.getY()+")");
//lblStatus.setText(String.format("(%d,%d)",event.getX(),event.getY()));
}
}
}

您正在创建并添加另一个JPanel,即mousePanel,并将其添加到DrawPanel JPanel中,该容器使用默认的FlowLayout。这使mousePanel的大小成为其首选大小,即[0,0],这意味着正在添加mousePanel组件,但它太小,无法被看到或执行任何重要操作。但是,为什么你甚至有或需要这个额外的JPanel?

解决方案:去掉mousePanel,不需要它。相反,将鼠标处理程序添加到this中。

附带问题,无需实现MouseMotionListener。MouseAdapter已经实现了此接口。

例如:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FooSwing02 extends JPanel {
private JLabel statusLabel = new JLabel("");
public FooSwing02() {
setPreferredSize(new Dimension(800, 650));
add(new JLabel("Mouse Location:"));
add(statusLabel);
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}

private class MyMouse extends MouseAdapter {
@Override
public void mouseMoved(MouseEvent event) {
Point p = event.getPoint();
String text = String.format("[%03d, %03d]", p.x, p.y);
statusLabel.setText(text);
}
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("GUI");
frame.add(new FooSwing02());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}

相关内容

  • 没有找到相关文章

最新更新