I am trying to add the MouseHandler
to my DrawPanel
class to eventually have a status label that updates the mouse location, but while using print statements, it seems like it is not registering any mouse input at all.
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()));
}
}
}
CodePudding user response:
You're creating and adding another JPanel, the mousePanel, and adding it to the DrawPanel JPanel, a container that uses the default FlowLayout. This makes the mousePanel's size its preferred size which is [0, 0] meaning that the mousePanel component is being added but it is too small to be seen or to do anything significant. But why do you even have or need this extra JPanel?
Solution: get rid of the mousePanel, there is no need for it. Instead add your mouse handler to this
.
Side issue, no need to implement MouseMotionListener. A MouseAdapter already implements this interface.
For example:
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("[d, d]", 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);
});
}
}