I want to display a value of a table column(which shows overall amount) in a labelfield.
Here is my code that i have used in developing a label
Border myBorder = BorderFactory.createBitmapBorder(
new XYEdges(20, 16, 27, 23),
Bitmap.getBitmapResource("border.png"));
LabelField myField = new LabelField("Total Amount Owed: Rs ",LabelField.USE_ALL_WIDTH | LabelField.FIELD_HCENTER)
{
protected void paint(Graphics g) {
g.setColor(Color.BLUE);
super.paint(g);
}
};
myField.setBorder(myBorder);
add(myField);
This is the sql statement i want to use to fetch the value from table:
Statement statementG56 = db.createStatement("SELECT owe FROM GTemp5");
statementG56.prepare();
statementG56.execute();
How to include that select statement into my labelfield so that the amount fetched stands beside the label title.
This is how i implemented. Hope it helps future readers.
try
{
//Open or create the database
Database db = DatabaseFactory.openOrCreate("database1.db");
Statement statementGF55 = db.createStatement("CREATE TABLE IF NOT EXISTS GTemp5(owe INTEGER)");
statementGF55.prepare();
statementGF55.execute();
statementGF55.close();
Statement statementGF56 = db.createStatement("SELECT owe FROM GTemp5");
statementGF56.prepare();
statementGF56.execute();
Cursor c = statementGF56.getCursor();
while(c.next())
{
System.out.println("Inside while for fetching total owed value");
Row r;
r = c.getRow();
Border myBorder = BorderFactory.createBitmapBorder(
new XYEdges(20, 16, 27, 23),
Bitmap.getBitmapResource("border.png"));
String pp = "" + r.getObject(0);
LabelField myField = new LabelField("Total Amount: Rs " +pp,LabelField.USE_ALL_WIDTH | LabelField.FIELD_HCENTER)
{
protected void paint(Graphics g)
{
g.setColor(Color.RED);
super.paint(g);
}
};
myField.setBorder(myBorder);
vfm.add(myField);
}
}
catch(Exception e)
{
System.out.println( e.getMessage() );
e.printStackTrace();
}
Related
I am trying to get certain row records from a db_table into an array list. though this has been done many times, mine is a bit more different.
suppose I have a table in my database like this below:
+---------+--------+--------+
| NAME | BILL | CONTACT|
+---------+--------+--------+
| james | 400 | 024669 |
| Mavis | 700 | 025550 |
| john | 650 | 029510 |
| bendo | 340 | 023579 |
+---------+--------+--------+
and I want an array to display records like this:
[james,400,024669]
[Mavis,700, 025550]
[John,650, 029510]
[bendoo,340,023579]
please how do I achieve that. the code I wrote gave me only a last array. and its:
ArrayList<String> inner = null;
try{
String sql="select Name,Score,Contact from members";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
inner = new ArrayList<>();
for(int i=1; i<=columnsNumber; i++){
inner.add(rs.getString(i));
}
}
System.out.println(inner);
}catch(Exception e){
}
but this is the only System.out.PrintIn displayed:
[bendoo,340,023579]
BUILD SUCCESSFUL (total time: 2 minutes 13 seconds)
please how do I get this below as my result:
[james,400,024669]
[Mavis,700, 025550]
[John,650, 029510]
[bendoo,340,023579]
You need to add inner to a global list. Otherwise you lose the row value every time, and keep only the last one.
Your code should be changed to something like:
ArrayList<String> inner = null;
try {
String sql = "select Name, Score, Contact from members";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
List<List<String>> allRows = new ArrayList<List<String>>(); // add this!
while (rs.next()) {
inner = new ArrayList<>();
for(int i=1; i<=columnsNumber; i++){
inner.add(rs.getString(i));
}
System.out.println("ROW: "+row); // Add this line.
allRows.add(inner); // add this line!
}
for (List<String> row : allRows) {
System.out.println(row);
}
} catch (SQLException e) {
e.printStackTrace();
}
please this is what I have fully so far..
ArrayList<String> inner = null;
try {
String sql = "select Name,Score, Contact from members";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
List<List<String>> allRows = new ArrayList<List<String>>(); // add this!
while (rs.next()) {
inner = new ArrayList<>();
for(int i=1; i<=columnsNumber; i++){
inner.add(rs.getString(i));
}
allRows.add(inner); // add this line!
}
for (List<String> row : allRows) {
System.out.println(row);
}
} catch (SQLException e) {
}
try{
// initialise SMS object.
ZenophSMS sms = new ZenophSMS();
sms.setUser("example#gmail.com");
sms.setPassword("xxxxxxx");
sms.authenticate();
// set message parameters.
sms.setMessage("Hello {$name}, your score is {$score} . please come for you money ");
sms.setSenderId("NICE ONE");
sms.setMessageType(MSGTYPE.TEXT);
// add destinations.
for ( ArrayList<String> recpt : allRows) sms.addRecipient(recpt.get(2), new String[] {recpt.get(0), recpt.get(1)}, false);
// submit the message. Since the total number of destinations is
// less than 400, the submit status of the destinations will be returned.
List<String[]> resp = sms.submit();
// show the status
for (String[] dest : resp)
{ REQSTATUS st = REQSTATUS.fromInt(Integer.parseInt(dest[0]));
if (null != st)
switch (st) {
case SUCCESS:
System.out.println("Submitted: %s"+ dest[1]);
break;
case ERR_INSUFF_CREDIT:
System.out.println("Insufficient Credits: %s"+dest[1]);
break;
default:
System.out.println("Failed: %s"+ dest[1]);
break;
}
}
}
catch (SMSException ex) { System.out.println("Error: " + ex.getMessage()); }
catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); }
this line cant find the array 'allRows'. please what do I do.its giving me an error message that variable cannot be found.
for ( ArrayList<String> recpt : allRows) sms.addRecipient(recpt.get(2),new String[] {recpt.get(0), recpt.get(1)}, false);
Move "inner = new ArrayList<>();" before the "while" statement. You are reinitializing the arraylist for every row.
In java, i am trying to delete the last row of my database. The database has 15 rows and i want to the delete the 15th one. The columns are called Initials and Score.
Intials Scores
rows# 1. ADS 2343
2. DDE 5454
15. TBK 332
I can't have it selecting TBK because i'm wanting it to delete the 15th one no matter what it is so a new one can be added. Everywhere I've looked it's always has to be specific or a delete all rows. Can anyone help? Many thanks to those who help. :)
Assuming id is an identity column
DELETE FROM table
WHERE id = (SELECT MAX(id) FROM table)
OP : I am trying to delete the last row of my database.
make resultset updatable : ResultSet.CONCUR_UPDATABLE);
set cursor to last record : resultSet.last();
delete last Record : resultSet.deleteRow();
for further use of rs you should set : resultSet.beforeFirst();
private static int delLastRow(ResultSet resultSet) {
if (resultSet == null) {
return 0;
}
try {
resultSet.last();
int delID = resultSet.getInt(1);
resultSet.deleteRow();
System.out.println("Deleted id :" + delID);
resultSet.beforeFirst();
return delID;
} catch (SQLException exp) {
exp.printStackTrace();
} finally {
try {
resultSet.beforeFirst();
} catch (SQLException exp) {
exp.printStackTrace();
}
}
return 0;
}
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//rs will be scrollable, will not show changes made by others,
//and will be updatable
String sql;
sql = "SELECT * FROM `order details`";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("Deleted id :"+ delLastRow(rs));
....
}
I try to refresh the data of jTable upon deletion of selected row. Here are my codes to set up table :
private JTable getJTableManageReplies() {
jTableManageReplies.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jTableManageReplies.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
int viewRow = jTableManageReplies.getSelectedRow();
// Get the first column data of the selectedrow
int replyID = Integer.parseInt(jTableManageReplies.getValueAt(
viewRow, 0).toString());
eForumRepliesAdmin reply = new eForumRepliesAdmin(replyID);
replyID = JOptionPane.showConfirmDialog(null, "Are you sure that you want to delete the selected reply? " , "Delete replies", JOptionPane.YES_NO_OPTION);
if(replyID == JOptionPane.YES_OPTION){
reply.deleteReply();
JOptionPane.showMessageDialog(null, "Reply has been deleted successfully.");
SetUpJTableManageReplies();
}
}
}
});
return jTableManageReplies;
}
public void SetUpJTableManageReplies() {
DefaultTableModel tableModel = (DefaultTableModel) jTableManageReplies
.getModel();
String[] data = new String[5];
db.setUp("IT Innovation Project");
String sql = "Select forumReplies.reply_ID,forumReplies.reply_topic,forumTopics.topic_title,forumReplies.reply_content,forumReplies.reply_by from forumReplies,forumTopics WHERE forumReplies.reply_topic = forumTopics.topic_id ";
ResultSet resultSet = null;
resultSet = db.readRequest(sql);
jTableManageReplies.repaint();
tableModel.getDataVector().removeAllElements();
try {
while (resultSet.next()) {
data[0] = resultSet.getString("reply_ID");
data[1] = resultSet.getString("reply_topic");
data[2] = resultSet.getString("topic_title");
data[3] = resultSet.getString("reply_content");
data[4] = resultSet.getString("reply_by");
tableModel.addRow(data);
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
}
And this is my sql statement :
public boolean deleteReply() {
boolean success = false;
DBController db = new DBController();
db.setUp("IT Innovation Project");
String sql = "DELETE FROM forumReplies where reply_ID = " + replyID
+ "";
if (db.updateRequest(sql) == 1)
success = true;
db.terminate();
return success;
}
I called the repaint() to update the table data with the newest data in database and it works. I mean the data after deletion of certain row. However, the existing posts will keep on re-add. Then I add the removeAllElement method to remove all the existing posts because my sql statement is select * from table. Then, there is an error message which is ArrayIndexOutOfBoundsException. Any guides to fix this? Thanks in advance.
I called the repaint() to update the table data with the newest data
in database and it works.
There is no need to call repaint method when data is changed. Data change is handled by the Table Model (DefaultTableModel in this case.) And fireXXXMethods are required to be called whenever data is changed but you are using DefaultTableModel even those are not required. (Since by default it call these methods when ever there is a change.)
I think the problem is in the valuesChanged(..) method. You are getting the value at row 0 but not checking whether table has rows or not. So keep a constraint.
int viewRow = jTableManageReplies.getSelectedRow();
// Get the first column data of the selectedrow
if(jTableManageReplies.getRowCount() > 0)
int replyID = Integer.parseInt(jTableManageReplies.getValueAt(viewRow, 0).toString());
I try to code a forum using java swing. Firstly, on click for the jTable, it will lead to eForumContent.class which pass in the id together.
jTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
int id = 0;
eForumTopics topics = new eForumTopics(id);
topics.retrieveDiscussion();
eForumThreadContent myWindow = new eForumThreadContent(id);
myWindow.getJFrame().setVisible(true);
}
});
I initialize the id first. But I set my id in database table to auto number. Then I call the retrieveDiscussion method to get the id from database and pass it to eForumThreadContent. Here are my codes for retrieveDiscussion method.
public boolean retrieveDiscussion(){
boolean success = false;
ResultSet rs = null;
DBController db = new DBController();
db.setUp("IT Innovation Project");
String dbQuery = "SELECT * FROM forumTopics WHERE topic_id = '" + id
+ "'";
rs = db.readRequest(dbQuery);
db.terminate();
return success;
}
}
Then, inside the eForumThreadContent, I want to display the content of chosen thread using a table. So I use the id which I pass in just now and insert into my sql statement. Here are my codes.
public eForumThreadContent(int id) {
this.id = id;
}
if (jTable == null) {
Vector columnNames = new Vector(); // Vector class allows dynamic
// array of objects
Vector data = new Vector();
try {
DBController db = new DBController();
db.setUp("IT Innovation Project");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String dsn = "IT Innovation Project";
String s = "jdbc:odbc:" + dsn;
Connection con = DriverManager.getConnection(s, "", "");
String sql = "Select topic_title,topic_description,topic_by from forumTopics WHERE topic_id = '"+id+"'";
java.sql.Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
((Connection) statement).close();
} catch (Exception e) {
System.out.println(e);
}
jTable = new JTable(data, columnNames);
TableColumn column;
for (int i = 0; i < jTable.getColumnCount(); i++) {
column = jTable.getColumnModel().getColumn(i);
if (i == 1) {
column.setPreferredWidth(400); // second column is bigger
}else {
column.setPreferredWidth(200);
}
}
String header[] = { "Title", "Description", "Posted by" };
for (int i = 0; i < jTable.getColumnCount(); i++) {
TableColumn column1 = jTable.getTableHeader().getColumnModel()
.getColumn(i);
column1.setHeaderValue(header[i]);
}
jTable.getTableHeader().setFont( new Font( "Dialog" , Font.PLAIN, 20 ));
jTable.getTableHeader().setForeground(Color.white);
jTable.getTableHeader().setBackground(new Color(102, 102, 102));
jTable.setEnabled(false);
jTable.setRowHeight(100);
jTable.getRowHeight();
jTable.setFont( new Font( "Dialog" , Font.PLAIN, 18 ));
}
return jTable;
}
However, the table inside eForumThreadContent is empty even when I clicked on certain thread. It also gives me an error message.
[Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
at DBController.database.DBController.readRequest(DBController.java:27)
at kioskeForum.entity.eForumTopics.retrieveDiscussion(eForumTopics.java:67)
at kioskeForum.ui.eForumDiscussion$3.mouseClicked(eForumDiscussion.java:296)
I research online to get an idea for topic views using id. But my table does not show up anything. Can somebody enlighten me how to fix it? Or any other ways to display topic views in java swing? Thanks in advance.
I know this may be stupid question i am gonna put here since i am a complete java noob. may be you guys can help me out to get this problem solved.
I am working on an application where a user would need the result dislayed on jsp page in pdf form, and the pdf is being generated as output stream in HTTP request, means when a user clicks on a button(on jsp) to generate PDF with result i.e. PDF getting generated on fly and sent to client browser.
Using iText, i am able to generate custom generated pdfs on the fly
Heres the Code snippet
public class PdfSample extends HttpServlet {
public PdfSample() {
super();
}
//connection to DB.... code goes here.....
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws javax.servlet.ServletException, java.io.IOException {
DocumentException ex = null;
ByteArrayOutputStream baosPDF = null;
try {
baosPDF = generatePDFDocumentBytes(req, this.getServletContext());
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("filename_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
resp.setHeader("Cache-Control", "max-age=30");
resp.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
sbContentDispValue.append("inline");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
resp.setHeader("Content-disposition", sbContentDispValue.toString());
resp.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = resp.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
} catch (DocumentException dex) {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.println(this.getClass().getName() + " caught an exception: "
+ dex.getClass().getName() + "<br>");
writer.println("<pre>");
dex.printStackTrace(writer);
writer.println("</pre>");
} finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
}
protected ByteArrayOutputStream generatePDFDocumentBytes(
final HttpServletRequest req, final ServletContext ctx)
throws DocumentException
{
Document doc = new Document();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
PdfWriter docWriter = null;
try {
docWriter = PdfWriter.getInstance(doc, baosPDF);
doc.addAuthor("Sample");
doc.addCreationDate();
doc.addProducer();
doc.addCreator("Sample");
doc.addTitle("Sample Report");
doc.setPageSize(PageSize.LETTER);
doc.open();
String strServerInfo = ctx.getServerInfo();
if (strServerInfo != null) {
}
doc.add(makeHTTPParameterInfoElement(req));
} catch (DocumentException dex) {
baosPDF.reset();
throw dex;
} finally {
if (doc != null) {
doc.close();
}
if (docWriter != null) {
docWriter.close();
}
}
if (baosPDF.size() < 1) {
throw new DocumentException("document has " + baosPDF.size()
+ " bytes");
}
return baosPDF;
}
protected Element makeHTTPParameterInfoElement(final HttpServletRequest req) {
Table tab = null;
tab = makeTable("", "White Color Car", "Black Color Car", "Total");
return (Element) tab;
}
private static Table makeTable(final String firstColumnTitle,
final String secondColumnTitle, final String thirdColumnTitle,
final String fourthColumnTitle) {
Paragraph paragraph, paragraph1;
int val1 = 0;
int val2 = 0;
int val3 = 0;
int val4 = 0;
Table tab = null;
try {
tab = new Table(4);
} catch (BadElementException ex) {
throw new RuntimeException(ex);
}
Cell c = null;
try {
paragraph = new Paragraph("Car Report");
paragraph.setAlignment(1);
c = new Cell(paragraph);
c.setColspan(tab.getColumns());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tab.setBorderWidth(1);
tab.setBorderColor(Color.BLACK);
tab.setPadding(2);
tab.setSpacing(3);
tab.setBackgroundColor(Color.WHITE);
tab.addCell(c);
tab.addCell(new Cell(firstColumnTitle));
tab.addCell(new Cell(secondColumnTitle));
tab.addCell(new Cell(thirdColumnTitle));
tab.addCell(new Cell(fourthColumnTitle));
tab.endHeaders();
String startDate1 = "01/06/2011";
String endDate1 = "11/09/2011";
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
try {
Date startDate = sdf1.parse(startDate1);
Date endDate = sdf1.parse(endDate1);
java.sql.Date sdate = new java.sql.Date(startDate.getTime());
java.sql.Date edate = new java.sql.Date(endDate.getTime());
String newWhiteColor = "select count(*) from .......";
String newBlackColor = "select count(*) from .......";
String totalWhiteColor= "select count(*) from .....";
String totalBlackColor = "select count(*) from .......";
Connection connection = null;
PreparedStatement preparedStatement = null;
PreparedStatement preparedStatement1 = null;
PreparedStatement preparedStatement2 = null;
PreparedStatement preparedStatement3 = null;
ResultSet resultSet = null;
ResultSet resultSet1 = null;
ResultSet resultSet2 = null;
ResultSet resultSet3 = null;
connection = getSimpleConnection1();
// New Car recently sold out - White Color
preparedStatement = connection
.prepareStatement(newWhiteColor);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
val1 = resultSet.getInt(1);
}
// New Car recently sold out - Black Color
preparedStatement3 = connection
.prepareStatement(newBlackColor);
resultSet3 = preparedStatement3.executeQuery();
while (resultSet3.next()) {
val2 = resultSet3.getInt(1);
}
// Total White Color cars sold out
preparedStatement1 = connection
.prepareStatement(totalWhiteColor);
resultSet1 = preparedStatement1.executeQuery();
while (resultSet1.next()) {
val3 = resultSet1.getInt(1);
}
// Total Black Color cars sold out
preparedStatement2 = connection
.prepareStatement(totalBlackColor);
resultSet2 = preparedStatement2.executeQuery();
while (resultSet2.next()) {
val4 = resultSet2.getInt(1);
}
Integer newWhite = val1;
Integer newBlack = val2;
Integer totalWhite = val3;
Integer totalBlack = val4;
Integer totalNewCars = newWhite + new Black;
Integer totalCars= totalWhite + totalBlack ;
tab.addCell(new Cell("New Cars Sold Out"));
tab.addCell(new Cell(newWhite.toString()));
tab.addCell(new Cell(newBlack.toString()));
tab.addCell(new Cell(totalNewCars.toString()));
tab.addCell(new Cell("Total Cars Sold out"));
tab.addCell(new Cell(totalWhite.toString()));
tab.addCell(new Cell(totalBlack.toString()));
tab.addCell(new Cell(totalCars.toString()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tab;
}
}
The Above code fetching the data (count) from the database by making the connection and displaying in cells. with the above code i am able to create pdf on fly and output as showing below.
--------------------------------------------------------------------------------------------------
Car Report
--------------------------------------------------------------------------------------------------
| White Color Car |Black Color Car | Total
--------------------------------------------------------------------------------------------------
New Cars Sold out| 5 | 8 | 13
--------------------------------------------------------------------------------------------------
Total Cars Sold Out| 6 | 4 | 10
--------------------------------------------------------------------------------------------------
Query 1) How Can I align the car report in Center?
Query 2) Data and text are being displayed inside a cell, how can i set the border of the cell to "0".
Query 3) How can i color a particular cell ( the blank one)?
Query 4) Is it possible to Insert a image on top of the header of the pdf?
Any help would be greatly appreciated !!!!!
Query 1) How Can I align the car report in Center?
Solution : c.setHorizontalAlignment(Element.ALIGN_CENTER);