The right rationale in Java

I tried to look, but I can not find a solution to my problem with justification. I want all transaction amounts that were included with 2 decimal places to be justified on the right, however nothing that I try seems to work. This is the result:

Java Dialog with Unbalanced Numbers

Transaction temp; String message = ""; for (int i = 0; i < checkAccnt.gettransCount(); i++) { temp = checkAccnt.getTrans(i); message += String.format("%-10d", temp.getTransNumber()); message += String.format("%-10d", temp.getTransId()); message += String.format("%10.2f", temp.getTransAmount()) + '\n'; } JOptionPane.showMessageDialog(null, message); 
+5
source share
2 answers

An alternative to using a font with a fixed width (as suggested in the comments) or different widgets with better alignment control (as suggested in another answer) can be replacing the space characters before the numbers with space characters that have the same width as the numbers (if the font has a fixed width for numbers, which looks like a screenshot):

 message += String.format("%-10d", temp.getTransNumber()).replace(' ', '\u2007'); 

See http://www.fileformat.info/info/unicode/char/2007/index.htm

+3
source

It seems that JTable may be better suited for what you are trying to do than just String.format()

 int rows = checkAccnt.size(); // guess as to the appropriate method name, but you get the idea int cols = 3;// based off of number of coloumns in the For statement JTable table = new JTable(rows, cols); DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer(); rightRenderer.setHorizontalAlignment(JLabel.RIGHT); table.getColumnModel().getColumn(3).setCellRenderer(rightRenderer); Transaction temp; String message = ""; for (int i = 0; i < checkAccnt.gettransCount(); i++) { temp = checkAccnt.getTrans(i); table.setValueAt(String.format("%-10d", temp.getTransNumber()), i, 0); table.setValueAt(String.format("%-10d", temp.getTransId()), i, 1); table.setValueAt(String.format("%10.2f", temp.getTransAmount()), i, 2); } JOptionPane.showMessageDialog(null, table); 
+1
source

Source: https://habr.com/ru/post/1244501/


All Articles