Number Format in Jtable - java

I have a Jtable (tableSummary).
I need to format 2 columns of the table so it's content is in DECIMAL form (e.g. 1,400.00)
How can i do it?
here's my code for the table:
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);
}
}
the columns, amt and daily are the columns i need to be formatted.
Thanks in Advance!

As kleopatra already suggested in her comments
The conversion from Object to a String representation (or any other representation) is the task of the renderer. Your TableModel should just contain the objects
Create and set the appropriate renderer on your JTable (for example by calling JTable#setDefaultRenderer or overriding JTable#getCellRenderer)
As renderer for your Number instances you can use one which uses the NumberFormat for formatting as shown in the answer of Samir

NumberFormat formatter = new DecimalFormat("#,###.00");
String str = formatter.format(1400);
System.out.println(str);

Related

How to clear all data inserted in a jTable

I designed a jTable that will display data from a table in MySql DB.
The table name is studentrolls with STRollID (int) as primary key and StudentID (Varchar), BachID (year) as foreign keys.
So after typing the StudentID in a jTextField and clicking a jButton only data concerning the student should be displayed in the jTable.
It's working actually but am having two problems, instead of displaying the Year on the year column it's displaying a date for example it should display 2020 but it displaying 2020-01-01.
The main problem is that when I enter another StudentID, it is adding the new results to the old one, so when I enter for the first time a StudentID I get good results and then when I enter another StudentID and click the button I get in the table the new results mixed with the first student's one, etc...
Is there any way to solve this and clear the table before inserting new results?
Here is my code :
private void rSButtonIconDsearchstidActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sqlqueryPastYHi = "SELECT * FROM studentrolls WHERE StudentID = ? ORDER BY BachID";
PreparedStatement preparedStatement = con.prepareStatement(sqlqueryPastYHi);
PreparedStatement pst=con.prepareStatement(sqlqueryPastYHi);
if(!jTextFieldsearchstid.getText().isEmpty() ) {
preparedStatement.setString(1, jTextFieldsearchstid.getText());
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
String scolaryear = resultSet.getString("BachID");
String stclass = resultSet.getString("ClassID");
String totpercent = String.valueOf(resultSet.getInt("PourcentTotal"));
String finalplace = String.valueOf(resultSet.getInt("PlaceFinale"));
String appication = resultSet.getString("Aplication");
String behavior = resultSet.getString("Conduite");
String finalaction = resultSet.getString("ActionFinale");
String pastHistTableData [] = {scolaryear, stclass, totpercent, finalplace, appication, behavior, finalaction};
DefaultTableModel tblModel = (DefaultTableModel)jTablehipastyears.getModel();
tblModel.addRow(pastHistTableData);
}
}
else{
JOptionPane.showMessageDialog(this, "Veillez taper le matricule d'un eleve svp.");
}
}catch (Exception exception){
JOptionPane.showMessageDialog(this, "erreur des donnees: " + exception.getMessage());
}
}
is there any way to solve this and clear the table before inserting new results?
DefaultTableModel tblModel = (DefaultTableModel)jTablehipastyears.getModel();
tblModel.setRowCount(0);
while (...)
{
....
tblModel.addRow(...);
}
thanks #camickr i did changed the code as follow using your methode and it worked.
if(!jTextFieldsearchstid.getText().isEmpty() ) {
preparedStatement.setString(1,
jTextFieldsearchstid.getText());
ResultSet resultSet = preparedStatement.executeQuery();
DefaultTableModel tblModel =
(DefaultTableModel)jTablehipastyears.getModel();
tblModel.setRowCount(0);
while(resultSet.next()){
String scolaryear = resultSet.getString("BachID");
String stclass = resultSet.getString("ClassID");
String totpercent =
String.valueOf(resultSet.getInt("PourcentTotal"));
String finalplace =
String.valueOf(resultSet.getInt("PlaceFinale"));
String appication =
resultSet.getString("Aplication");
String behavior = resultSet.getString("Conduite");
String finalaction =
resultSet.getString("ActionFinale");
String pastHistTableData [] = {scolaryear, stclass,
totpercent, finalplace, appication, behavior,
finalaction};
tblModel.addRow(pastHistTableData);
}

Show results on Jtable between dates when selected Jdatechooser (Mysql)

This is the query for the (between dates). But when I select the dates and click OK all records on JTable disappears. Help me to build the query and statement for the get record between dates on JTable.
Jtable with records
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here
// java.util.Date val1 = jDateChooser1.getDate();
// java.util.Date val2 = jDateChooser2.getDate();
java.sql.Date val1 = new java.sql.Date(jDateChooser1.getDate().getTime());
java.sql.Date val2 = new java.sql.Date(jDateChooser2.getDate().getTime());
try {
String sql = "select * from Umar where Date between ? and ? ";
pst = conn.prepareStatement(sql);
pst.setDate(1, val1);
pst.setDate(2, val2);
rs = pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null,e);
}
}
Once again we know nothing about your database. It is up to you to know how the data is displayed in the database.
Here is a simple query to get you started.
String sql = "Select * from Umar";
PreparedStatement ps = connection.prepareStatement();
ResultSet rs = ps.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
System.out.println( md.getColumnLabel(i) );
}
// Get row data
while (rs.next())
{
for (int i = 1; i <= columns; i++)
{
Object data = rs.getObject(I);
System.out.println(data + " : " + data.getClass());
}
}
rs.close();
stmt.close();
This has absolutely nothing to do with your JTable. It is just a query of the database. So get this query working. Determine how the date is stored in your database. Is it a String or a Date?
Then next you change the query:
String sql = "Select * from Umar where Date between ? and ? ";
...
ps.setDate/String(1, ...);
ps.setDate/String(2, ...);
Then you test this with a hard coded data to make sure you get data. Then once this step is working you fix your program that loads the data into the JTable.

SQLite syntax error with JTable

Hi want to to create a JTable with SQLite Database. The data should come from a SQLite database and are stored in this . Now new details to be added by typing in a text field . However, I get the error message : "java.sql.SQLException: near "(": syntax error"
What´s wrong?
public class SQLite {
public static DefaultTableModel model = new DefaultTableModel();
private static JTextField fieldID;
private static JTextField fieldName;
private static JTextField fieldAge;
private static JTextField fieldAddress;
private static JTextField fieldSalary;
public static void main( String args[] ) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
c.commit();
JFrame f = new JFrame();
f.setLayout(new GridLayout(5,1));
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
fieldID = new JTextField("ID");
fieldName = new JTextField("Name");
fieldAge = new JTextField("Age");
fieldAddress = new JTextField("Address");
fieldSalary = new JTextField("Salary");
String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
"VALUES (fieldID.getText(), feldName.getText(), Age.getText(), feldAddress.getText(), feldSalary.getText()";
stmt.executeUpdate(sql);
JTable table = new JTable(model);
f.add( new JScrollPane( table ) );
model.addColumn("id");
model.addColumn("name");
model.addColumn("age");
model.addColumn("address");
model.addColumn("salary");
ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
model.addRow(new Object[] {id, name, age, address, salary});
}
/**JTextField feldID = new JTextField("ID");
JTextField feldName = new JTextField("Name");
JTextField feldAge = new JTextField("Age");
JTextField feldAddress = new JTextField("Address");
JTextField feldSalary = new JTextField("Salary");
**/
f.pack();
f.setVisible( true );
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
Here is your problem :
"VALUES (fieldID.getText(), feldName.getText(), Age.getText(), feldAddress.getText(), feldSalary.getText()";
They're read as litterals and not as a reference to a getter.
Here is what you'll have to replace it with by using concatenation.
"VALUES ("+fieldID.getText()+","+feldName.getText()+","+Age.getText()+","+feldAddress.getText()+","+feldSalary.getText()+");";
Use a PreparedStatement. It is easier to code and maintain and will manage the delimiters for you:
String sql = "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) VALUES (?, ?, ?, ?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, fieldID.getText() );
stmt.setString( 2, fieldname.getText() );
stmt.setString( 3, ... );
stmt.setString( 4, ... );
stmt.setString( 5, ... );
stmt.executeUpdate();
but now i get the java sql Exception: "no such column: ID"
Well, the message is self explanatory. There is no "ID" column. We can't help you with that because only you know the proper names of the columns since you are the one that created the database.

How to display multiple items on one graph?

I have designed an inventory/sales information system using a Swing GUI for a computer store (fictional). One of the features is to display a basic bar graph of how certain products have sold in a year.
The data is called from a MySQL database called dbsales and the category of products is selected using a jComboBox (cboAnSales).
I have a method (public void graph()) that has the coding to generate the graph.
The data for the items displays in textfields and the graph uses that information to display. The method is called inside the cboAnSalesif statements for each category.
The problem now is it generates each item on its own graph. For example there are 7 items in the Cables category and when I select it, it generates 7 graphs (one for each item).
I need all 7 items to display on one single graph.
How can I achieve this?
Here is the Cables section of the cboAnSales:
private void cboAnSalesActionPerformed(java.awt.event.ActionEvent evt) {
if (cboAnSales.getSelectedIndex() == 1)
{
try
{
String sql = "select * from dbsales where category ='" + "Cable" + "'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/salventri","root","password");
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
DefaultListModel model = new DefaultListModel();
while(rs.next())
{
String ID = rs.getString("pid");
txtpid.setText(ID);
String brand = rs.getString("pbrand");
txtBrand.setText(brand);
String name = rs.getString("pname");
txtName.setText(name);
String category = rs.getString("category");
txtCategory.setText(category);
String unitSold = rs.getString("usold");
txtUnitsSold.setText(unitSold);
graph();
}
}
catch (Exception e)
{
}
}
Here is the coding for my graph in the public void graph() method:
String unitsSold = txtUnitsSold.getText();
String brand = txtBrand.getText();
String name = txtName.getText();
String cat = txtCategory.getText();
DefaultCategoryDataset ddataset = new DefaultCategoryDataset();
ddataset.setValue(new Double(unitsSold), cat, brand + " " + name);
JFreeChart chart = ChartFactory.createBarChart3D("Annual Sales Performance", cat, "Number of Units Sold", ddataset);
chart.getTitle().setPaint(Color.RED);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.BLUE);
ChartFrame frame2 = new ChartFrame("Annual Sales", chart);
frame2.setVisible(true);
frame2.setSize(450,350);
With credit to WillShackleford, the solution to my question resulted in the following code in my public void graph():
public void graph()
{
String year = cboAnnYear.getSelectedItem().toString();
if(cboAnSales.getSelectedIndex() == 1)
{
try
{
//declaring the type of category in the column
String text = "Cable";
//Select statement getting the row count
String sql = "select count(category) from dbsales where category ='" + text + "'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/salventri","root","password");
PreparedStatement stmt = con.prepareStatement("select * from dbsales where category=?");
stmt.setString(1, text);
ResultSet rs = stmt.executeQuery();
DefaultCategoryDataset ddataset = new DefaultCategoryDataset();
while (rs.next())
{
ddataset.setValue(new Double(rs.getDouble("usold")),
rs.getString("pbrand") + " " + rs.getString("pname"),
rs.getString("syear"));
}
JFreeChart chart = ChartFactory.createBarChart3D("Annual Sales Performance", text, "Number of Units Sold", ddataset);
chart.getTitle().setPaint(Color.RED);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.BLUE);
ChartFrame frame2 = new ChartFrame("Annual Sales", chart);
frame2.setVisible(true);
frame2.setSize(900,700);
}

Column Currency Format on DefaultTableModel

I'm trying to use a DefaultTableModel and place in a column format, but not make changes.
How I can put Currency format in a column in a DefaultTableModel?
String iSql = "SELECT cod_pro, name_pro, price_pro,stock_pro from product";
String[] r = {"ID","Product","Price","Stock"};
String [] Data = new String[4];
model = new DefaultTableModel(null,r);
try{
Statement jSt = jcn.Con().createStatement();
ResultSet jRst = jSt.executeQuery(iSql);
while(jRst.next()){
Data[0] = jRst.getString("cod_pro");
Data[1]= jRst.getString("name_pro");
Data[2]= jRst.getString("price_pro");
Data[3]= jRst.getString("stock_pro");
modelo.addRow(Data);
}
tblProduct.setModel(model);
TableColumnModel m = tblProduct.getColumnModel();
m.getColumn(2).setCellRenderer(NumberRenderer.getCurrencyRenderer());
}
catch(SQLException ex)
{
JOptionPane.showMessageDialog(null, "ERROR " + ex);
}
I really don`t know a method to do what you want but you could do a trick like this
Data[2]= "Currency"+jRst.getString("price_pro");
but when your retrieving data you have to split it or substring it

Categories