I am using
String.format("w:%5d h:%5d n:%5d",a,b,c);
to show space padded int
s in a JLabel
as the mouse moves over a JFrame
. Thinking it might be a label artifact, I added a JFormattedTextField
for good measure but it suffers with the same problem: the text dances around as the coords change from single to multi-digit. How to solve this?
Here's some example code
package all.code.classes;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
public class rough3 {
static String toString(int a,int b,int c)
{
return String.format("w:%5d h:%5d n:%5d",a,b,c);
}
JFormattedTextField ftf=new JFormattedTextField();
JLabel la=new JLabel();
static int x,y;
public static void main(String[] args) {
SwingUtilities.invokeLater(()-> {
rough3 xx = new rough3();
xx.la.setHorizontalAlignment(SwingConstants.RIGHT);
JFrame fr = new JFrame();
fr.setLayout(new BorderLayout());
fr.getContentPane().add(xx.ftf, BorderLayout.SOUTH);
fr.getContentPane().add(xx.la, BorderLayout.NORTH);
fr.setSize(500, 100);
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
x = e.getX();
y = e.getY();
xx.ftf.setText(xx.toString(x,y,1));
xx.la.setText(xx.toString(x,y,135));
}
});
});
}
}
You should add these lines.
xx.ftf.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
xx.la.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));