带有空格的JAVA填充字符串(JFrame)

时间:2013-12-22 14:51:18

标签: java swing

我正在为某些应用程序编写SWING GUI。在我的应用程序中,我有两个字段显示一些数字。这是我的JFrame上的当前结果:

12345678 -12,231

1234 -123.000

但是,我希望它是这样的:

12345678 -12,231

1234 -123.000

我首先计算第一列的长度并填充空白以获得我想要的长度。但结果是我在上面展示的第一个结果。在JFrame上显示时,似乎不同的字符占用不同的长度。对此有何想法?或者它与字体有关?谢谢!

2 个答案:

答案 0 :(得分:1)

基于此图片

enter image description here

我建议您遇到的问题是字体是可变宽度字体,这意味着每个字符都有自己的宽度(因此1小于2)。< / p>

在这种情况下,您最好使用GridLayoutGridBagLayout

例如......

enter image description here

JFrame frame = new JFrame("Testing");

frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets  = new Insets(4, 4, 4, 4);
gbc.anchor = gbc.WEST;

frame.add(new JLabel("12345678"), gbc);
gbc.gridx++;
frame.add(new JLabel("-12,231"), gbc);

gbc.gridy++;
gbc.gridx = 0;
frame.add(new JLabel("1234"), gbc);
gbc.gridx++;
frame.add(new JLabel("-123.000"), gbc);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

或者,如果这只是一点点,你可以尝试将文本格式化为HTML ...

enter image description here

JFrame frame = new JFrame("Testing");
frame.setLayout(new BorderLayout());

StringBuilder sb = new StringBuilder(128);
sb.append("<html><table>");
sb.append("<tr><td>12345678</td>-12,231<td></tr>");
sb.append("<tr><td>1234</td>-123.000<td></tr>");
sb.append("</table></html>");

frame.add(new JLabel(sb.toString()));

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

或者只使用JTable

答案 1 :(得分:0)

非常简单,请看一下:

public static String padRight(String s, int n) {
     return String.format("%1$-" + n + "s", s);  
}

public static String padLeft(String s, int n) {
    return String.format("%1$" + n + "s", s);  
}


public static void main(String args[]) throws Exception {
 System.out.println(padRight("Howto", 20) + "*");
 System.out.println(padLeft("Howto", 20) + "*");
}
/*
  output :
     Howto               *
                    Howto*
*/