簡體   English   中英

帶空白的JAVA填充字符串(JFrame)

[英]JAVA padding string with whitespace (JFrame)

我正在為某些應用程序編寫SWING GUI。 在我的應用程序中,我有兩個顯示一些數字的字段。 這是我的JFrame上的當前結果:

12345678 -12,231

1234 -123.000

但是,我希望它是這樣的:

12345678 -12,231

1234 -123.000

我首先計算第一列的長度,並在空白處填充所需的長度。 但是結果是我上面顯示的第一個。 看起來,當顯示在JFrame上時,不同的字符占據不同的長度。 有什么想法嗎? 還是和字體有關? 謝謝!

根據這張圖片

在此處輸入圖片說明

我建議您遇到的問題是該字體是可變寬度的字體,這意味着每個字符都有其自己的寬度(因此1小於2 )。

在這種情況下,最好使用GridLayoutGridBagLayout

例如...

在此處輸入圖片說明

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 ...

在此處輸入圖片說明

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

真的很簡單,看一下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM