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
Related
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);
}
I'm trying to display the data from a access database; for some reason, whenever I run the program, only one row is displayed. Here's my code
try{
String coursec = jTextField9.getText().trim();
String sql5 = "SELECT * FROM Studentcourse WHERE ccode ='" +coursec+"'";
String url5 ="jdbc:ucanaccess://C:/Users/james_000/Documents/NetBeansProjects/Registration/Campus.accdb ";
Connection conn5 =DriverManager.getConnection(url5);
Statement statem = conn5.createStatement();
ResultSet rs5 = statem.executeQuery(sql5);
while (rs5.next()){
DefaultTableModel dm;
dm = new DefaultTableModel(10, 10);
String coursecode= rs5.getString(2);
String attend =rs5.getString(3);
String date =rs5.getString(4);
Vector <String> vector = new Vector<String>();
vector.add(coursecode);
vector.add(attend);
vector.add(date);
String s[] = new String[]{"ccode", "stnumattend", "Date"};
dm.setColumnIdentifiers(s);
jTable1.setModel(dm);
dm.addRow(vector);
jTable1.setVisible(true);
}
}
catch(Exception d){
System.err.println("Exception:" + d.getMessage());
}
You're creating a new DefaultTableModel each time through your while loop, so only the last such model is applied to jTable1. At a minimum, move the model creation out of the loop.
DefaultTableModel dm = new DefaultTableModel(10, 10);
jTable1.setModel(dm);
while (rs5.next()) {
String coursecode= rs5.getString(2);
…
}
I want result value in java is Int like in IBM Data Studio, but in my case is java generate value in double, i don't know why?, Please help to fix it!
This my java code to generate Number in table
private void polDatToTab(ResultSet rs, JTable table) throws SQLException{
String[] colHead = new String[] {"No","NIK","Nama"};
DefaultTableModel tm = new DefaultTableModel();
ResultSetMetaData rsd = rs.getMetaData();
Vector<String> nameCol = new Vector<String>();
int kolCount = rsd.getColumnCount();
for(int i=0;i<colHead.length;i++){
nameCol.add(colHead[i]);
}
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while(rs.next()){
Vector<Object> vec = new Vector<Object>();
for(int j=1;j<=kolCount;j++){
vec.add(rs.getObject(j));
}
data.add(vec);
}
tm.setDataVector(data, nameCol);
table.setModel(tm);
}
This my java code to display Table in Gui
private void srcEmp(){
String srcE = "SELECT (#ROW_NUMBER:=#ROW_NUMBER + 1) AS No_Urut,NIK,NAMA FROM PAYROLL.KARYAWAN,"
+ "(SELECT #ROW_NUMBER:=0) AS T WHERE NAMA LIKE '%"+srcRes+"%'";
DbConnect co = new DbConnect();
co.connectDB();
try {
st = co.connection.createStatement();
ResultSet ul = st.executeQuery(srcE);
polDatToTab(ul, tabResSrc);
} catch (SQLException ex) {
Logger.getLogger(ResSrc.class.getName()).log(Level.SEVERE, null, ex);
}
}
This my sql code in IBM Data Studio generate true value in int
SELECT (#ROW_NUMBER:=#ROW_NUMBER + 1) AS No_Urut,NIK,NAMA
FROM PAYROLL.KARYAWAN,(SELECT #ROW_NUMBER:=0) AS T
WHERE NAMA LIKE '%"+srcRes+"%'
This my Result in Java Gui:
and This my Result in IBM Data Studio
Your polDatToTab method isn't generic, it looks like it's designed to work only with this particular resultset. I am jumping to that conclusion because of this line
String[] colHead = new String[] {"No","NIK","Nama"};
As such, you are aware that the first column is expected to be an int. Therefore,
vec.add(rs.getInt(1));
for(int j=2; j<=kolCount; j++){
vec.add(rs.getObject(j));
}
Does the trick
I wrote a program in java to retrieve images and text data from a table. Everything is right, only when i try to retrieve an image(Blob) from the table, i get an exhausted result set error.I tried google it, but the explanation was fa too condensed. Can anyone help me with this? I will appreciate a nice explanation.
Here is the code
try {
Class.forName(classforname);
Connection con = DriverManager.getConnection(Connectionurl, username, password);
String sql = "Select * from teacherdata where teachername='" + tf1.getText() + "'";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
rs.next();
String thename = rs.getString("teachername");
String sub1, sub2, sub3, sub4;
sub1 = rs.getString("sub1");
sub2 = rs.getString("sub2");
sub3 = rs.getString("sub3");
sub4 = rs.getString("sub4");
String sql2 = "select tid,tpic from teacherimages where teachername='" + tf1.getText() + "'";
PreparedStatement ps2 = con.prepareStatement(sql2);
ResultSet rs2 = ps2.executeQuery(sql2);
rs2.next();
String Tid = rs2.getString("tid");
Blob b = rs.getBlob("tpic");
byte barr
[] = new byte[(int) b.length()]; //an array is created but contains no data
barr = b.getBytes(3, (int) b.length());
Image im = jInternalFrame1.getToolkit().createImage(barr);
ImageIcon icon = new ImageIcon(im);
JLabel label = new JLabel(icon);
Object[] row = {
thename,
sub1,
sub2,
sub3,
sub4,
b,
Tid,
icon
};
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
jTable1.setVisible(true);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(SearchBox.class.getName()).log(Level.SEVERE, null, ex);
}
You are not checking the return value of next on the ResultSet.
Please consider changing your code to
if(result.next()){
// the logic
}
EDIT
Further on the code change , please check that your tables are not empty. If your tables are empty you will not return values.
The error Exhausted Resultset set occurs when you attempt to access the result set after iterating or not checking if the result set returns data
while (resultSet.next()) {
//result set logic
}
//
resultset.getString[1] //<- will throw error Exhausted Resultset
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);