我有一个Jtable(tableSummary)。 我需要格式化表格的2列,使其内容为DECIMAL格式(例如1,400.00) 我该怎么办?
这是我的表格代码:
private void tableMarketMouseClicked(java.awt.event.MouseEvent evt) {
String sql = "SELECT tblClientInfo.ClientID, tblrefmarket.MarketDesc, tblclientinfo.LastName, tblledger.LoanAmount, "
+ "tblledger.DateStarted, tblledger.DailyPay, tblledger.Expiry FROM tblclientinfo Inner Join tblbusinessinfo ON tblbusinessinfo.ClientID = tblclientinfo.ClientID "
+ "Inner Join tblrefmarket ON tblbusinessinfo.MarketID = tblrefmarket.MarketID "
+ "Inner Join tblledger ON tblledger.ClientID = tblclientinfo.ClientID where MarketDesc = ?";
try {
//add column to the table model
model.setColumnCount(0); //sets the column to 0 para ig utro click, dili mapun-an ang columns
model.setRowCount(0); //sets the row to 0 para ig utro click, dili mapun-an ang rows
model.addColumn("C NO");
model.addColumn("MARKET");
model.addColumn("BORROWER");
model.addColumn("LOAN");
model.addColumn("START");
model.addColumn("DAILY");
model.addColumn("EXPIRY");
//model.addColumn("BALANCE");
int row = tableMarket.getSelectedRow();
pst = conn.prepareStatement(sql);
pst.setString(1, tableMarket.getModel().getValueAt(row, 0).toString());
rs = pst.executeQuery();
while(rs.next()){
String id = rs.getString(1);
String market = rs.getString(2);
String name = rs.getString(3);
String amt = rs.getString(4);
String start = rs.getString(5);
String daily = rs.getString(6);
String expiry = rs.getString(7);
//String area = rs.getString(3);
model.addRow(new Object[]{ id, market, name, amt, start, daily, expiry});
}
tableSummary.setModel(model);
renderer.setHorizontalAlignment( JLabel.RIGHT );
renderer2.setHorizontalAlignment( JLabel.CENTER );
tableSummary.getColumnModel().getColumn(0).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(4).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(6).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(3).setCellRenderer( renderer );
tableSummary.getColumnModel().getColumn(5).setCellRenderer( renderer );
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
列,amt和daily是我需要格式化的列。
提前致谢!
答案 0 :(得分:4)
正如kleopatra在她的评论中已经提出的那样
TableModel
应该只包含对象JTable
上创建并设置相应的渲染器(例如,通过调用JTable#setDefaultRenderer
或覆盖JTable#getCellRenderer
)作为Number
个实例的渲染器,您可以使用NumberFormat
进行格式化的渲染器,如Samir的答案所示
答案 1 :(得分:2)
NumberFormat formatter = new DecimalFormat("#,###.00");
String str = formatter.format(1400);
System.out.println(str);