简体   繁体   中英

JAVA padding string with whitespace (JFrame)

I am writing SWING GUI for some applications. In my application, I have two fields showing some numbers. This is the current result on my JFrame:

12345678 -12,231

1234 -123.000

However, I want it to be like this:

12345678 -12,231

1234 -123.000

I first calculate the length of the first column and pad the whitespace to make the length I want. But the result is the first one I showed above. It seems that different characters occupy different length when displayed on the JFrame. Any idea about this? Or does it have something to do with the font? Thank you!

Based on the this image

在此处输入图片说明

I would suggest the problem you're having is the fact that the font is a variable width font, meaning that each character has it's own width (so 1 is smaller the 2 ).

In this case, you would probably be better of using a GridLayout or GridBagLayout

For example...

在此处输入图片说明

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

Or if that's just a little too much, you could just try formating the text as HTML...

在此处输入图片说明

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

Or just use a JTable

its really easy, take a look:

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*
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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