This sample adds a JButton and a JLabel to a JFrame.
There is also a JComponent that should show the cursor's XY coordinates.
I know there are samples out there showing how to show the XY coordinates but am curious to know why it fails in this scenario.
Looking at the output, it appears that all the required listeners are firing as the output even shows the paintCompoent() getting executed with the expected output.
Not sure if it was required, but I did try to setVisible(true) as well as setBounds().
What is it that is prevents the JComponent with the XY coordinates from appearing.
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class XYCoordinateTest extends JFrame
{
JLabel label = new JLabel("My Test Label");
JButton b1 = new JButton("Press Me");
XYMouseLabel xy = new XYMouseLabel();
class XYMouseLabel extends JComponent
{
public int x;
public int y;
public XYMouseLabel()
{
this.setBackground(Color.BLUE);
}
// use the xy coordinates to update the mouse cursor text/label
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
String s = x + ", " + y;
System.out.println("paintComponent() : " + s);
g.setColor(Color.red);
g.drawString(s, x, y);
}
}
public XYCoordinateTest ()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(label);
getContentPane().add(b1);
xy.setBounds(0, 0, 300, 100);
xy.setVisible(true);
getContentPane().add(xy);
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent me)
{
System.out.println("Panel Mouse Move x : " + me.getX() + " Y : " + me.getY());
xy.x = me.getX();
xy.y = me.getY();
xy.repaint();
}
});
pack();
setSize(300, 100);
}
public static void main(String[] args) {
new XYCoordinateTest().setVisible(true);
}
}
The xy component doesn't have a preferred size. You call pack on the JFrame, which sizes components to their preferred sizes. Since the xy component doesn't have one, it becomes invisible.