Asociation between Rows in GRidRows and Rows in Datatable of Grid Object
Hi all.
Anyone knows how to get the row number in datatable from a row in the Gridrows collection?
I´m trying to get data from selected rows but I can`t do it.
Thaks for the help.
Sorry. I haven`t seen the GetDataTableRowIndex method in UI help files
Similar Messages
-
Transpose columns and rows / Switch columns and rows
Hello,
Is it possible to interchange columns and rows in order to create a left-to-right scrolling table instead of a top-to-bottom scrolling one?
In detail:
I have this:
| col 1 | col 2 | col 3
row 1 | | |
row 2 | | |
row 3 | | |
... | | |
...and want to have this:
| row 1 | row 2 | row 3 | ...
col 1 | | | |
col 2 | | | |
col 3 | | | |
Does anyone know if this is possible with the standard table or the ALV?
Thanks in advance & Kind regards,
RobertHi,
So there is no easy solution by just setting a flag in the ALV config!? ...too bad!
As for the dynamic creation:
Would there be an issue with different data types in one "column" (former row)? As a matter of fact there probably will be a mix of character, numbers, ...
Regards,
Robert -
Can we hide the lines between the columns and rows of an alv in wd abap
HI all ,
I know that we can colour cell/column/row in an alv in wd abap.
but, can we hide the lines between the columns and rows of an alv in wd abap.
i have checked this link [hiding lines b/n rows and columns of an alv|http://help.sap.com/saphelp_nw04/helpdata/en/91/e7eb40c4f8712ae10000000a155106/content.htm]
but didn't understand, can please anybody provide some example or any material..? it will be very helpful.
THANK YOU.
Edited by: arfat111 on Feb 15, 2010 7:05 AMCode some like this in the WDDOINIT method of your view which defines the ALV component as used component.
instansiate the ALV component
data lo_cmp_usage type ref to if_wd_component_usage.
lo_cmp_usage = wd_this->wd_cpuse_usage_alv().
if lo_cmp_usage->has_active_component() is initial.
lo_cmp_usage->create_component().
endif.
data lo_interfacecontroller type ref to iwci_salv_wd_table.
lo_interfacecontroller = wd_this->wd_cpifc_usage_alv().
data lo_value type ref to cl_salv_wd_config_table.
lo_value = lo_interfacecontroller->get_model().
hide the grid lines
lo_value->if_salv_wd_table_settings~SET_GRID_MODE( value = '01' ).
Thanks,
Abhishek -
Setting the ALV Hierarchy tree with grid line between the columns and rows
Hi Experts,
I would like to ask if there is any suggestion on setting the ALV hierarchy tree to be separated by grid line between the columns and rows just like how it is display the same way in normal ALV grid.
Thanks in advance.Hi Lin,
The requirement which you have stated is not possible.
Lin,
Also i have a query regarding BADI ZME_PROCESS_REQ_CUST, which you had raised on SDN. You have marked the question as solved/answered.
Changing the data of a customize field in purchase requisition
Could you please let me know, the steps you did to update the screen fields through the BADI.
I would really appreciate your reply, because i am facing exactly the same problem which you have mentioned.
Thanks,
Best regards,
Prashant -
Multiple columns and rows in MessageService
I am attempting to create a message (via MessageService) which has multiple lines of data, and each line has multiple data columns.
Background: My program reads data from a web store, and creates Sales Orders in SBO. A single run might process multiple orders. When all orders have been entered, the program should send a (single) message to a list of recipients. The message will have one line of data for each sales order produced. Each line will contain two fields: the linked SBO sales order number, and the unlinked web order number.
When the message is initially created, I'm defining the multiple columns and initializing the data lines:
pMessageDataColumns = oMessage.MessageDataColumns
pMessageDataColumn = pMessageDataColumns.Add()
pMessageDataColumn.ColumnName = "SalesOrder"
pMessageDataColumn.Link = BoYesNoEnum.tYES
pMessageDataColumn = pMessageDataColumns.Add()
pMessageDataColumn.ColumnName = "WebOrder"
pMessageDataColumn.Link = BoYesNoEnum.tNO
oLines = pMessageDataColumn.MessageDataLines()
Later, as each Sales Order is processed, I'm attempting to inject the two data values into the message data:
oLine = oLines.Add()
oLine.Value = Str(pOrd.DocNum)
oLine.Object = 17
oLine.ObjectKey = Str(pOrd.DocEntry)
oLine = oLines.Add()
oLine.Value = pOrd.WebOrder
The above code would be invoked for each Sales Order processed. However, it generates an "Internal error (-5002) occurred" when the message is ultimately sent.
The SDK documentation states:
The MessageDataLine is a child data structure related to the MessageDataColumn. It contains the value of a specified cell in the Data table, which is defined by its column number (vtIndex of Item of MessageDataColumns) and row number (vtIndex of Item of MessageDataLines).
I guess I don't understand the relationship between adding a "line" in my data display versus adding data into a "column". It appears that the "oLines.Add()" is used to bump across the columns of the data. If so, how do I advance to the next entire row of data in the message?
Thanks, DaveClass Item
Public ItemCode As String
Public Dscription As String
End Class
Dim ItemCodes as new list( of item)
Dim one as new item
one.ItemCode = "ItemCode"
one. Dscription ="Name of Item"
itemcodes.add (one)
Try
Dim oCmpSvc As SAPbobsCOM.CompanyService = _ocmp.GetCompanyService()
Dim oMsgSvc As SAPbobsCOM.MessagesService = oCmpSvc.GetBusinessService(ServiceTypes.MessagesService)
Dim oMsg As SAPbobsCOM.Message = oMsgSvc.GetDataInterface(MessagesServiceDataInterfaces.msdiMessage)
oMsg.Subject = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
oMsg.Text = Msg
Dim oMsgDataColumn As SAPbobsCOM.MessageDataColumn
If ItemCodes.Count > 0 Then
oMsgDataColumn = oMsg.MessageDataColumns.Add()
oMsgDataColumn.ColumnName = "Product / Item Code"
oMsgDataColumn.Link = BoYesNoEnum.tYES
For Each oneitem As Item In ItemCodes
Dim oMsgDataLine As SAPbobsCOM.MessageDataLine = oMsgDataColumn.MessageDataLines.Add()
oMsgDataLine.Object = "4"
oMsgDataLine.ObjectKey = oneitem.ItemCode
oMsgDataLine.Value = oneitem.Dscription
Next
oMsgDataColumn = oMsg.MessageDataColumns.Add()
oMsgDataColumn.ColumnName = "Description"
oMsgDataColumn.Link = BoYesNoEnum.tNO
For Each oneitem As Item In ItemCodes
Dim oMsgDataLine As SAPbobsCOM.MessageDataLine = oMsgDataColumn.MessageDataLines.Add()
oMsgDataLine.Value = oneitem.Dscription
Next
End If
Dim oMsgRecipient As SAPbobsCOM.Recipient = oMsg.RecipientCollection.Add()
oMsgRecipient.UserCode = "manager"
oMsgRecipient.SendInternal = BoYesNoEnum.tYES
oMsgRecipient.SendEmail = BoYesNoEnum.tNO
oMsgSvc.SendMessage(oMsg)
MsgBox("SAP B1 internal Message sent...")
Catch ex As Exception
MsgBox("Unable to send SAP B1 internal message. Error:" + ex.Message)
End Try
End Sub -
Read words from text file by delimiter as columns and rows
Hi All,
I need your help as i have a problem with reading string by delimiter. i have used various tech in java, but i can not get the result as expected.
Please help me to get the string from text file and write into excel . i have used a text file.
problem
get the below as string by delimiter
OI.ID||'|'||OI.IDSIEBEL||'|'||OI.IDTGU||'|'||OI.WORKTYPE||'|'||OI.UTR_FK
read the below as string by delimiter
"50381|TEST_7.15.2.2|09913043548|Attivazione|07-SEP-10
now i need to write the above into excel file as columns and rows.
there are 5 columns and each corresponding values
the outut excel should be
OI.ID OI.IDSIEBEL OI.IDSIEBEL OI.WORKTYPE OI.UTR_FK
50381 TEST_7.15.2.2 09913043548 Attivazione 07-SEP-10
i tried in diffrerent techinq but not able to get the resule. pls help me
Thanks,
Jasmin
Edited by: user13836688 on Jan 22, 2011 8:13 PMFirst of all, when posting code, put it between two tags.
Second of all, the pipe is a special character in regex, so you need to escape it as
.split("\ \|");
Erh. So 2 backslashes before the pipe character. Stupid forum won't post it.
Edited by: Kayaman on Jan 24, 2011 9:35 AM
Edited by: Kayaman on Jan 24, 2011 9:35 AM
Edited by: Kayaman on Jan 24, 2011 9:36 AM -
Creating even columns and rows in flash
I need to create a grid in flash using the drawing tools. The
grid has multiple (10+) columns and rows. Other than using the
ruler and guides is there a way to ensure even spacing with columns
and rows?Create the lines for the columns and locate the two end lines
where they need to be using the Properties panel X positioning.
Then, with the remaining lines placed between the two end lines,
select all the lines and use the align tool to space them evenly.
Do similarly for the row lines, but on a separate layer. You can
move them to the column layer afterwards. -
Difference of ViewObjectScope,RowSetScope and Row Scope
I am reading The uix help online and get a understanding problem(Business Components for Java Integration):
What is the Difference between ViewObjectScope,RowSetScope and Row Scope? And how to use RowSetScope and RowScope
<bc4j:appModuleScope name="alpha" >
<contents>
<bc4j:viewObjectScope name="beta" > <contents>
<!-- indexed children scoped by View Object "beta", in Application Module "alpha". --> ... <bc4j:rowSetScope name="gamma" > <contents>
... <!-- indexed children scoped by Row Set "gamma", of View Object "beta", in Application Module "alpha". --> ... <bc4j:rowScope name="delta" > <contents>
... <!-- indexed children scoped by Row "delta" of Row Set "gamma", of View Object "beta", in Application Module "alpha". --> ... </contents>
</bc4j:rowScope>
</contents>
</bc4j:rowSetScope>
</contents>
</bc4j:viewObjectScope> </contents></bc4j:appModuleScope>Hi Yong,
I think the best way to understand the different scopes is by example. Run the uiXML for Business Components "Complete uiXML Application" wizard to automatically generate uiXML pages bound to one or more ViewObjects. For example, you could generate Business Components for the EMP and DEPT sample tables, and then generate a uiXML Application for those Business Components.
At the top of each uiXML for Business Component's page you will see a registryDef section that defines what application module and view objects the page uses.
The UIX BC4J elements like textInput, choice, column, etc, all have an attrName attribute. Specifying this attribute will tell UIX to retrieve the data for this element from BC4J. However, an attribute name is not enough to uniquely identify where the data should come from. This is where the scopes come in. UIX figures out what application module, and view object, to look for the attrName by the heirarchy of scope elements surrounding the element on which attrName was used.
For example:
<bc4j:rootAppModuleScope name="EmpAppModule">
<contents>
<form name="TextInputform">
<contents>
<bc4j:viewObjectScope name="EmpView">
<contents>
<ui:stackLayout>
<contents>
<bc4j:textInput name="txt1"
attrName="Ename" />
</contents>
</ui:stackLayout>
</contents>
</bc4j:viewObjectScope>
</contents>
</form>
</contents>
</bc4j:rootAppModuleScope>
This code binds a text input to the value of the EName attribute of the current row of the EmpView view object in the EmpAppModule application module (where EmpView and EmpAppModule are defined in the registryDef section of the page).
The rowScope element defines the scope to be the row with the given name (if no such row is available, it is created with the default values given for each attribute).
The rowSetScope allows you to specify the name of a BC4J rowSet and a child "rowStamp" UIX element that will be rendered (stamped out) for each row in the rowSet. -
Query to get rows betwen x and y + table total row count
Hi,
I try get rows between e.g. 100 and 150 when I sort by some column
My query is now like this
SELECT *
FROM
(SELECT a.*,
row_number() OVER (ORDER BY OWNER ASC) rn,
COUNT(1) over() mrn
FROM (SELECT * FROM all_objects) a
WHERE ROWNUM BETWEEN least(100,mrn) AND 150It is not very fast if I run that kind select from big table
Any tips to optimize this query?
Regards,
JariHi,
I'm so bad with SQL :(
Here is sample where I need that kind query.
http://actionet.homelinux.net/htmldb/f?p=100:504
It looks standard Apex report but it is not.
It is just test to use query to output html using htp package
I send parameter start row, max rows, column I like order by.
Now I do query for cursor
/* Report query */
l_sql := '
SELECT * FROM(
SELECT a.*, row_number() OVER (ORDER BY '
|| l_sort_col
|| ' '
|| l_sort_ord
|| ') rn, COUNT(1) over() mrn
FROM(' || l_sql || ') a
) WHERE rn BETWEEN LEAST(' || l_start_row || ',mrn) AND ' || l_last_row
;Then I loop cursor and output html.
You can order report by click heading and there is that pagination
I did not know that I could find examples by "pagination query" =), thanks for that tip for both of you.
I know Apex have reports ,
but I need have features that Apex templates can not provide at least yet.
So I have study that generating html tables using custom package instead Apex report should be best approach to get layouts I need.
Regards,
Jari
Edited by: jarola on Jan 21, 2011 10:38 PM -
Rows per batch and DefaultbufferMaxrows
Hi,
What is the difference between rows per batch and DefaultbufferMaxrows in data task? Is there any relation between these two?Rows per batch : It is the number of rows fetched under single operation to optimize the query plan.The rows per batch should be as close to to total amount of records in your source table.
The default value for this setting is -1 which specifies all incoming rows will be treated as a single batch. You can change this default behavior and break all incoming rows into multiple batches. The allowed value is only positive integer which specifies
the maximum number of rows in a batch.
DefaultBufferMaxRows : Defines the maximum number of rows in each buffer, by setting the
DefaultBufferMaxRows property. The default maximum number of rows is 10,000.
References:
http://www.mssqltips.com/sqlservertip/1840/sql-server-integration-services-ssis-best-practices/
http://social.msdn.microsoft.com/forums/sqlserver/en-US/86efc54e-45bd-4ccc-baf1-a7b34f80fe32/rows-per-batch-property
If this post answers your query, please click "Mark As Answer" or "Vote as Helpful". -
Hi,
how to do the difference between row chaining and row migrate.
In what table may i see the difference.http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:4423420997870
-
Interactive Report Column Headings and Row Height
I am using the div style="width:350px;" method to control the width of columns in various interactive reports. That works fine except for the following:
1. When creating filters, the <div...> stuff shows up along with the actual column heading, thus confusing some end users
2. Even when I uncheck the "Use same text for single row view" checkbox and then provide a simple single row view label, the <div> stuff still shows up on the single row view
Does anyone have a better solution?
Also, does anyone know of a way to limit the row height within an interactive report row? I have some columns of data that contain a large amount of HTML data and I'd like to be able to limit the number of rows that show on the report.
Is Oracle planning to provide some better control over the Interactive Report columns in another version? The Interactive Report is such a huge improvement in usability in APEX - it would be great to take it to another level by providing some better control over column width and row height.
Edited by: DaleB on Jun 18, 2009 8:54 AM
Edited by: DaleB on Jun 18, 2009 8:54 AMDale,
Unfortunately we don't have much we can use to do what you would like. I would have said it's impossible until version 4 but you could actually do something similar to what Roel has done. His trick is in the edit button. He changed the edit button to use an "onload" call to a JavaScript process. You could do the same but call a process that goes across the rows and styles each column. Now because you don't have a way to identify the column (can't use the order because the end user could change it) you'll have to write the code to look at the top row first and then style the appropriate column. As far as I can tell, this would be quite difficult and inefficient. Having said that if you need it that bad and would like some help with it, put up an example application on apex.oracle.com and provide the workspace/username/password and I'll take a look.
Regards,
Dan
http://danielmcghan.us
http://sourceforge.net/projects/tapigen
You can reward this reply by marking it as either Helpful or Correct ;-) -
how to show employee names in descending order but 3rd row is fixed and always top on the table ?
for example employee names is A,B,C, D, E
and output is C,E,D,B,ASince you are posting in the design forum, the short answer is - you don't. Rows in a table have no inherent order that you can rely on and the "position" of rows is a visual characteristic that should be implemented by the application that displays
this information or by the query that is used to generate the resultset.
So the next question is how one accomplishes this particular order within a select statement. That is a tsql question which, for future reference, is best posted to the tsql forum. In addition, many of the questions or issues that you will face
have been discussed in the forums - often many, many times. The first thing you should do when faced with an issue is to simply search the forums and leverage the the knowledge that has already been discussed. In doing so you are quite likely to
see suggestions or related issues that you should consider in your search for a solution.
Now, to answer the question - you need to formulate a order by clause that forces the rows to be sorted in the manner you desire. Effectively you have 2 levels of sorting. The first level divides your rows into 2 groups. Group 1 consists
of rows where name = E and Group 2 is everything else. Following that you then need to sort the rows in each group by name in descending order. Something like:
order by case name when E then 1 else 2 end, name desc -
How to enter a data into the specified column and row in a created table
Hi,
I want to enter some data to specified column and row in a already created table. Please let me know how to do this.
Regards
Shivakumar SinghA table is just a 2D array of strings. Keep it in a shift register and use "replace array element" to modify the desired entry programmatically.
If you want to modify it manually and directly from the front panel, make it into a control and type directly into the desired element. (In this case your program would need to write to it using a local variable).
Atttached is a simple example in LabVIEW 7.0 that shows both possibilities.
LabVIEW Champion . Do more with less code and in less time .
Attachments:
ChangeTableEntries.vi 41 KB -
Print JTable with Multiple pages and rows
I took the printing example at http://java.sun.com/developer/onlineTraining/Programming/JDCBook/advprint.html#pe and modified it a bit to include the following:
1) To Print Multiple pages
2) To wrap lines that is too long for the column
3) To print with a more proffesional style, so that it doesn't look like a screen capture is printed
4) To align the numbers to the right and center column headings
import javax.swing.*;
import javax.swing.table.*;
import java.awt.print.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.Dimension;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import java.text.*;
public class Report implements Printable
private final int LEFT_ALIGN = -1;
private final int CENTER_ALIGN = 0;
private final int RIGHT_ALIGN = 1;
private JFrame frame;
private JTable tableView;
private String lastPrintDate;
private Font defaultFont;
private Font headerFont;
private Font footerFont;
private int headerHeight;
private int footerHeight;
private int cellBuffer = 5;
private boolean first_pass;
private ArrayList pages;
public Report()
frame = new JFrame("Sales Report");
frame.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
final String[] headers =
"ID",
"Description",
"open price",
"latest price",
"End Date",
"Quantity"
int count = 0;
final Object[][] data =
{new Integer(count++), "Box of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of Biros ppppppppppppppp", "1.00", "4.99", new Date(), new Integer(200000)},
{new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
{new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
{new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
{new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
{new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
{new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
{new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
{new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
{new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
{new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
{new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
{new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
{new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
{new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
{new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
{new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
{new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
{new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
{new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
{new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
{new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
{new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
{new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
{new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
{new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
{new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
{new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
{new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
{new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
{new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)}
TableModel dataModel = new AbstractTableModel()
public int getColumnCount() { return headers.length; }
public int getRowCount() { return data.length;}
public Object getValueAt(int row, int col)
return data[row][col];
public String getColumnName(int column)
return headers[column];
public Class getColumnClass(int col)
return getValueAt(0,col).getClass();
public boolean isCellEditable(int row, int col)
return (col==1);
public void setValueAt(Object aValue, int row, int column)
data[row][column] = aValue;
tableView = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(tableView);
scrollpane.setPreferredSize(new Dimension(500, 80));
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(BorderLayout.CENTER,scrollpane);
frame.pack();
JButton printButton= new JButton();
printButton.setText("print me!");
frame.getContentPane().add(BorderLayout.SOUTH,printButton);
// for faster printing turn double buffering off
RepaintManager.currentManager(frame).setDoubleBufferingEnabled(false);
printButton.addActionListener( new ActionListener()
public void actionPerformed(ActionEvent evt)
doPrint();
frame.setVisible(true);
* Reset variables before printing
private void prepareForPrint()
pages = new ArrayList();
first_pass = true;
* Display a print dialog with some hardcoded defaults
* The print fonts are also hardcoded
public void doPrint()
try
String jobName = "Java Report";
defaultFont = new Font("Arial", Font.PLAIN, 8);
footerFont = new Font("Arial", Font.PLAIN, 6);
headerFont = new Font("Arial", Font.BOLD, 10);
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(this);
PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
prnSet.add(new Copies(1));
prnSet.add(new JobName(jobName, null));
prnSet.add(MediaSizeName.ISO_A4);
PageFormat pf = prnJob.defaultPage();
pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
prnJob.setJobName(jobName);
PrintService[] services = PrinterJob.lookupPrintServices();
if (services.length > 0)
if (prnJob.printDialog(prnSet))
* Get print date
String dateFormat = "dd/MM/yyyy HH:mm:ss";
DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
lastPrintDate = m_DateFormat.format(new Date()).toString();
prepareForPrint();
prnJob.print(prnSet);
else
JOptionPane.showMessageDialog(frame, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
return;
catch (PrinterException e)
e.printStackTrace();
public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
* Check if this is the first time the print method is called for this print action.
* It is not guaranteed that the print will be called with synchronous pageIndex'es,
* so we need to calculate the number of pages and which rows appear on which pages.
* Then the correct page will be printed regardless of which pageIndex is sent through.
if (first_pass)
calcPages(g, pageFormat);
first_pass = false;
// Stop printing if the pageIndex is out of range
if (pageIndex >= pages.size())
return NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
// The footer will be one line at the bottom of the page, cater for this.
g2.setFont(footerFont);
footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
g2.setFont(defaultFont);
FontMetrics fontMetrics = g2.getFontMetrics();
int fontHeight = fontMetrics.getHeight();
int fontDescent = fontMetrics.getDescent();
double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
double pageWidth = pageFormat.getImageableWidth();
double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
// Shrink or expand the table to fit the page width
double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
// Calculate the width in pixels for each column
double[] columnWidths = new double[tableView.getColumnCount()];
for(int i = 0; i < tableView.getColumnCount(); i++)
columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
// Reset the view to the start of the page
g2.translate(0, 0);
// Draw a rectangle to see the printable area
g2.draw3DRect((int)pageFormat.getImageableX(),
(int)pageFormat.getImageableY(),
(int)pageFormat.getImageableWidth(),
(int)pageFormat.getImageableHeight(),
false);
// Calculate the header height
g2.setFont(headerFont);
fontMetrics = g2.getFontMetrics();
// Print the headers and retreive the starting position for the data
int next_row = printLine(g2, pageFormat, fontMetrics, -1, (int)pageFormat.getImageableY() + fontHeight, columnWidths);
g2.setFont(defaultFont);
fontMetrics = g2.getFontMetrics();
// Start printing the detail
ArrayList page = (ArrayList)pages.get(pageIndex);
int start = ((Integer)page.get(0)).intValue();
int end = ((Integer)page.get(1)).intValue();
for (int i = start; i <= end; i++)
next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
// Print the footer
g2.setFont(footerFont);
String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
g2.drawString(pageFooter,
(int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
(int)(pageHeight - fontDescent));
return PAGE_EXISTS;
* We can't guarantee that the same amount of rows will be displayed on each page,
* the row heights are dynamic and may wrap onto 2 or more lines.
* Thus we need to calculate the height of each row and then test how may rows
* fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
// The footer will be one line at the bottom of the page, cater for this.
g2.setFont(footerFont);
footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
g2.setFont(defaultFont);
FontMetrics fontMetrics = g2.getFontMetrics();
int fontHeight = fontMetrics.getHeight();
int fontDescent = fontMetrics.getDescent();
double pageHeight = pageFormat.getImageableHeight() - fontHeight;
double pageWidth = pageFormat.getImageableWidth();
double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
// Shrink or expand the table to fit the page width
double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
// Calculate the width in pixels for each column
double[] columnWidths = new double[tableView.getColumnCount()];
for(int i = 0; i < tableView.getColumnCount(); i++)
columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
// Calculate the header height
int maxHeight = 0;
g2.setFont(headerFont);
fontMetrics = g2.getFontMetrics();
for (int j = 0; j < tableView.getColumnCount(); j++)
String value = tableView.getColumnName(j).toString();
int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
if (numLines > maxHeight)
maxHeight = numLines;
headerHeight = g2.getFontMetrics().getHeight() * maxHeight;
g2.setFont(defaultFont);
fontMetrics = g2.getFontMetrics();
int pageNum = 0;
int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
int prev_row = 0;
int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
int i = 0;
ArrayList page = new ArrayList();
page.add(new Integer(0));
for (i = 0; i < tableView.getRowCount(); i++)
maxHeight = 0;
for (int j = 0; j < tableView.getColumnCount(); j++)
String value = tableView.getValueAt(i, j).toString();
int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
if (numLines > maxHeight)
maxHeight = numLines;
prev_row = next_row;
next_row += (fontHeight * maxHeight);
// If we've reached the bottom of the page then set the current page's end row
if (next_row > bottom_of_page)
page.add(new Integer(i - 1));
pages.add(page);
page = new ArrayList();
page.add(new Integer(i));
pageNum++;
next_row = (int)pageFormat.getImageableY()
+ fontHeight
+ ((int)pageFormat.getHeight() * pageNum)
+ headerHeight;
bottom_of_page = (int)(pageFormat.getImageableHeight()
+ pageFormat.getImageableY())
+ ((int)pageFormat.getHeight() * pageNum)
- footerHeight;
//Include the current row on the next page, because there is no space on this page
i--;
page.add(new Integer(i - 1));
pages.add(page);
* Print the headers or a row from the table to the graphics context
* Return the position of the row following this one
public int printLine(Graphics2D g2,
PageFormat pageFormat,
FontMetrics fontMetrics,
int rowNum,
int next_row,
double[] columnWidths)
throws PrinterException
int lead = 0;
int maxHeight = 0;
for (int j = 0; j < tableView.getColumnCount(); j++)
String value = null;
int align = LEFT_ALIGN;
if (rowNum > -1)
Object obj = tableView.getValueAt(rowNum, j);
if (obj instanceof Number)
align = RIGHT_ALIGN;
value = obj.toString();
else
align = CENTER_ALIGN;
value = tableView.getColumnName(j);
int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
if (numLines > maxHeight)
maxHeight = numLines;
if (fontMetrics.stringWidth(value) < columnWidths[j])
// Single line
int offset = 0;
// Work out the offset from the start of the column to display alignment correctly
switch (align)
case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
default: offset = 0; break;
g2.drawString(value,
lead + (int)(pageFormat.getImageableX() + offset),
next_row);
else
for(int a = 0; a < numLines; a++)
//Multi-Line
int x = 0;
int width = 0;
for(x = 0; x < value.length(); x++)
width += fontMetrics.charWidth(value.charAt(x));
if (width > columnWidths[j])
break;
int offset = 0;
// Work out the offset from the start of the column to display alignment correctly
switch (align)
case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
default: offset = 0; break;
g2.drawString(value.substring(0, x),
lead + (int)(pageFormat.getImageableX() + offset),
next_row + (fontMetrics.getHeight() * a));
value = value.substring(x);
lead += columnWidths[j] + cellBuffer;
// Draw a solid line below the row
g2.draw(new Line2D.Double(pageFormat.getImageableX(),
next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent(),
pageFormat.getImageableY() + pageFormat.getImageableWidth(),
next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent()));
// Return the position of the row following this one
return next_row + (fontMetrics.getHeight() * maxHeight);
public static void main(String[] args)
new Report();
}Fixed some bugs and added a title. Just pass in a JTable and the class will do the rest.
import javax.swing.*;
import javax.swing.table.*;
import java.awt.print.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import java.text.*;
import java.math.*;
public class PrintJTable implements Printable
private final int LEFT_ALIGN = -1;
private final int CENTER_ALIGN = 0;
private final int RIGHT_ALIGN = 1;
private JFrame m_parent;
private String m_title;
private JTable tableView;
private String lastPrintDate;
private Font defaultFont;
private Font headerFont;
private Font footerFont;
private int headerHeight;
private int footerHeight;
private int cellBuffer = 5;
private boolean first_pass;
private ArrayList pages;
public PrintJTable(JFrame parent, JTable table)
m_parent = parent;
tableView = table;
doPrint();
public PrintJTable(JFrame parent, String title, JTable table)
m_parent = parent;
m_title = title;
tableView = table;
doPrint();
* Reset variables before printing
private void prepareForPrint()
pages = new ArrayList();
first_pass = true;
* Display a print dialog with some hardcoded defaults
* The print fonts are also hardcoded
public void doPrint()
try
String jobName = "Java Report";
defaultFont = new Font("Arial", Font.PLAIN, 8);
footerFont = new Font("Arial", Font.PLAIN, 6);
headerFont = new Font("Arial", Font.BOLD, 8);
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(this);
PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
prnSet.add(new Copies(1));
prnSet.add(new JobName(jobName, null));
prnSet.add(MediaSizeName.ISO_A4);
PageFormat pf = prnJob.defaultPage();
pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
prnJob.setJobName(jobName);
PrintService[] services = PrinterJob.lookupPrintServices();
if (services.length > 0)
if (prnJob.printDialog(prnSet))
* Get print date
String dateFormat = "dd/MM/yyyy HH:mm:ss";
DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
lastPrintDate = m_DateFormat.format(new Date()).toString();
prepareForPrint();
prnJob.print(prnSet);
else
JOptionPane.showMessageDialog(m_parent, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
return;
catch (PrinterException e)
e.printStackTrace();
public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
* Check if this is the first time the print method is called for this print action.
* It is not guaranteed that the print will be called with synchronous pageIndex'es,
* so we need to calculate the number of pages and which rows appear on which pages.
* Then the correct page will be printed regardless of which pageIndex is sent through.
if (first_pass)
calcPages(g, pageFormat);
first_pass = false;
// Stop printing if the pageIndex is out of range
if (pageIndex >= pages.size())
return NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
// The footer will be one line at the bottom of the page, cater for this.
g2.setFont(footerFont);
footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
g2.setFont(defaultFont);
FontMetrics fontMetrics = g2.getFontMetrics();
int fontHeight = fontMetrics.getHeight();
int fontDescent = fontMetrics.getDescent();
double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
double pageWidth = pageFormat.getImageableWidth();
double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
// Shrink or expand the table to fit the page width
double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
// Calculate the width in pixels for each column
double[] columnWidths = new double[tableView.getColumnCount()];
double test = 0;
for(int i = 0; i < tableView.getColumnCount(); i++)
columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
test += columnWidths;
// Reset the view to the start of the page
g2.translate(0, 0);
// Draw a rectangle to see the printable area
g2.draw3DRect((int)pageFormat.getImageableX(),
(int)pageFormat.getImageableY(),
(int)pageFormat.getImageableWidth(),
(int)pageFormat.getImageableHeight(),
false);
// Calculate the header height
g2.setFont(headerFont);
fontMetrics = g2.getFontMetrics();
// Print the headers and retreive the starting position for the data
int next_row = (int)pageFormat.getImageableY() + fontMetrics.getHeight();
if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
g2.drawString(m_title,
(int)(pageFormat.getImageableX()),
next_row);
Color current_color = g2.getColor();
g2.setColor(Color.lightGray);
int y = next_row + fontMetrics.getDescent();
g2.draw(new Line2D.Double(pageFormat.getImageableX(),
y,
(pageFormat.getImageableY() + pageFormat.getImageableWidth()),
y));
g2.setColor(current_color);
next_row += fontMetrics.getHeight();
next_row = printLine(g2, pageFormat, fontMetrics, -1, next_row, columnWidths);
g2.setFont(defaultFont);
fontMetrics = g2.getFontMetrics();
// Start printing the detail
ArrayList page = (ArrayList)pages.get(pageIndex);
int start = ((Integer)page.get(0)).intValue();
int end = ((Integer)page.get(1)).intValue();
for (int i = start; i <= end; i++)
next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
// Print the footer
g2.setFont(footerFont);
String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
g2.drawString(pageFooter,
(int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
(int)(pageHeight - fontDescent));
return PAGE_EXISTS;
* We can't guarantee that the same amount of rows will be displayed on each page,
* the row heights are dynamic and may wrap onto 2 or more lines.
* Thus we need to calculate the height of each row and then test how may rows
* fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
// The footer will be one line at the bottom of the page, cater for this.
g2.setFont(footerFont);
footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
g2.setFont(defaultFont);
FontMetrics fontMetrics = g2.getFontMetrics();
int fontHeight = fontMetrics.getHeight();
int fontDescent = fontMetrics.getDescent();
double pageHeight = pageFormat.getImageableHeight() - fontHeight;
double pageWidth = pageFormat.getImageableWidth();
double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
// Shrink or expand the table to fit the page width
double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
// Calculate the width in pixels for each column
double[] columnWidths = new double[tableView.getColumnCount()];
for(int i = 0; i < tableView.getColumnCount(); i++)
columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
// Calculate the header height
int maxHeight = 0;
g2.setFont(headerFont);
fontMetrics = g2.getFontMetrics();
headerHeight = 0;
if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
headerHeight = fontMetrics.getHeight();
for (int j = 0; j < tableView.getColumnCount(); j++)
String value = tableView.getColumnName(j).toString();
int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
if (numLines > maxHeight)
maxHeight = numLines;
headerHeight += g2.getFontMetrics().getHeight() * maxHeight;
g2.setFont(defaultFont);
fontMetrics = g2.getFontMetrics();
int pageNum = 0;
int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
int prev_row = 0;
int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
int i = 0;
ArrayList page = new ArrayList();
page.add(new Integer(0));
for (i = 0; i < tableView.getRowCount(); i++)
maxHeight = 0;
for (int j = 0; j < tableView.getColumnCount(); j++)
String value = formatObject(tableView.getValueAt(i, j));
int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
if (numLines > maxHeight)
maxHeight = numLines;
prev_row = next_row;
next_row += (fontHeight * maxHeight);
// If we've reached the bottom of the page then set the current page's end row
if (next_row > bottom_of_page)
page.add(new Integer(i - 1));
pages.add(page);
page = new ArrayList();
page.add(new Integer(i));
pageNum++;
next_row = (int)pageFormat.getImageableY()
+ fontHeight
+ ((int)pageFormat.getHeight() * pageNum)
+ headerHeight;
bottom_of_page = (int)(pageFormat.getImageableHeight()
+ pageFormat.getImageableY())
+ ((int)pageFormat.getHeight() * pageNum)
- footerHeight;
//Include the current row on the next page, because there is no space on this page
i--;
page.add(new Integer(i - 1));
pages.add(page);
* Print the headers or a row from the table to the graphics context
* Return the position of the row following this one
public int printLine(Graphics2D g2,
PageFormat pageFormat,
FontMetrics fontMetrics,
int rowNum,
int next_row,
double[] columnWidths)
throws PrinterException
int lead = 0;
int maxHeight = 0;
for (int j = 0; j < tableView.getColumnCount(); j++)
String value = null;
int align = LEFT_ALIGN;
if (rowNum > -1)
Object obj = tableView.getValueAt(rowNum, j);
if (obj instanceof Number)
align = RIGHT_ALIGN;
value = formatObject(obj);
else
//align = CENTER_ALIGN;
value = tableView.getColumnName(j);
int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
if (numLines > maxHeight)
maxHeight = numLines;
if (fontMetrics.stringWidth(value) < columnWidths[j])
// Single line
int offset = 0;
// Work out the offset from the start of the column to display alignment correctly
switch (align)
case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
default: offset = 0; break;
g2.drawString(value,
lead + (int)(pageFormat.getImageableX() + offset),
next_row);
else
for(int a = 0; a < numLines; a++)
//Multi-Line
int x = 0;
int width = 0;
for(x = 0; x < value.length(); x++)
width += fontMetrics.charWidth(value.charAt(x));
if (width > columnWidths[j])
break;
int offset = 0;
// Work out the offset from the start of the column to display alignment correctly
switch (align)
case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))); break;
case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))) / 2; break;
default: offset = 0; break;
g2.drawString(value.substring(0, x),
lead + (int)(pageFormat.getImageableX() + offset),
next_row + (fontMetrics.getHeight() * a));
value = value.substring(x);
lead += columnWidths[j] + cellBuffer;
// Draw a solid line below the row
Color current_color = g2.getColor();
g2.setColor(Color.lightGray);
int y = next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent();
g2.draw(new Line2D.Double(pageFormat.getImageableX(),
y,
(pageFormat.getImageableY() + pageFormat.getImageableWidth()),
y));
g2.setColor(current_color);
// Return the position of the row following this one
return next_row + (fontMetrics.getHeight() * maxHeight);
public String formatObject(Object obj)
String value = (obj == null) ? "" : obj.toString();
return value;
Maybe you are looking for
-
Laserjet 5000n on 10.4.11
I am new to Macs, though very conversant with PCs. At work I find an oldish Mac Pro, intel processor 2 x 2.66, 10GB memory and running OS X 10.4.11. There is an HP Laserjet 5000n attaached which has 68MB memory. Wired connection to network Printin
-
I have a jsp app and it lost session when I try to popup new window Googled around, millions of results but no helps It seems problem is in my IE 8 If anyone has expeience with the issue, please give me a help. Thank you Edited by: mycoffee on Jul 28
-
Hi All, I am new to tuning. Can somebody help me in tuning this SQL query. SELECT pppd.productid, pppd.sequencenumber, pppd.priceareaid, pppd.startdate, pppd.qtyfrom, pppd.enddate, pppd.price, pppd.articleid, pppd.customerid, pppd.distributorid, pppd
-
Pavilion dv4 Cd drive not working
Hi guys about two months ago my cd drive decided to stop read my my cds as well as to stop burning disc. Ive tried updating it and cleaning the eye and i know that its not the cds because they work on my desktop. the funny thing is that the drive do
-
How we import oracle 10g dump to oracle 9i
Hi Expert I want to import oracle 10g dump to oracle 9i is it possible ?????????? but how Thanks Madhvesh