繁体   English   中英

尽管在 Swing 组件中使用了 String.format,但格式仍会摆动

[英]Formatting wiggle inspite of using String.format in Swing component

我在用

String.format("w:%5d h:%5d n:%5d",a,b,c);

当鼠标移过JFrame时,在JLabel中显示空格填充的int 考虑到它可能是 label 工件,我添加了一个JFormattedTextField以作为很好的衡量标准,但它遇到了同样的问题:随着坐标从单数变为多位数,文本会四处跳动。 如何解决这个问题?

这是一些示例代码

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));

                }
            });

        });
    }




}



您应该添加这些行。

xx.ftf.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
xx.la.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM