Print in Cursor
I have written Cursor to fetch some values ,when i try to use Print in my cursor it throws an error. Can any one help me in executing my cursor? Like to know whether we can use Print statment in Cursor. Any links to e-books will also be helpful
Thanks
Durai
I would advise anyone working with Oracle to bookmark the online documentation, ideally in a Firefox bookmarks toolbar folder named something like "Oracle RTFM", containing at the very least,
Documentation Home
SQL Reference
PL/SQL Reference
Supplied PL/SQL Packages
Utilities
although
Performance Tuning Guide and others are also worth knowing about.
The above links are for 10.1, but there is online documentation going back to 7.3.
Similar Messages
-
Print only cursor-selected area of a PDF in Acrobat Pro, just as it is psbl to do in a browser
Hi
I want to print only cursor-selected area of a PDF in Acrobat Pro. That could be both text and images, which are in my selection. Just as it is psbl to do in a browser. Is it possible in Acrobat PRO?
I am using the latest Acrobat Pro 11.0.9Thanks for your effort but this again clearly does NOT answer my question. I do see a particular problem and that is that I might want to select text and images over a range of multiple pages. In a doc of 20 pages I might want to make a single selection of the text starting PRECISELY at the MIDDLE of page 2 and then continue dragging my selection all the way to PRECISELY the MIDDLE of page 15, thereby selecting all text and images within the precise range of my selection. That is some 13 pages there and I want to print out ONLY THAT selection of text and images. And in that case I cannot use your suggestion with the marquee zoom. Do you get me?
-
Cursor bind variable syntax err
Any one help me in correcting the syntax, for cursor return.
Oracle version 10g
I am trying to execute the sproc and print the cursor results using bind variable, I am getting he below error
Variable V_REFCUR REFCURSOR
Variable V_REFCUR2 REFCURSOR
variable swp_ret_value NUMBER
exec DELETE_POSITION(0,0,2,'U',:swp_ret_value,:V_REFCUR,:V_REFCUR2)
print swp_ret_value
Print v_refcur
Print v_refcur2
-- output
Error starting at line 5 in command:
exec DELETE_POSITION(0,0,2,'U',:swp_ret_value,:V_REFCUR,:V_REFCUR2)
Error report:
Cursor is closed.
SWP_RET_VALUE
V_REFCUR
V_REFCUR2
------Edited by: NeilCSE on Jan 18, 2011 4:08 AMit is calling another proc
PROCEDURE Assign_outRefcur2 (CurrentCursor IN OUT SYS_REFCURSOR
, v_ref_cur IN OUT SYS_REFCURSOR
, v_ref_cur2 IN OUT SYS_REFCURSOR
AS
InitCursor SYS_REFCURSOR;
BEGIN
IF NOT v_ref_cur%IsOpen THEN v_ref_cur := CurrentCursor;
ELSIF NOT v_ref_cur2%IsOpen THEN v_ref_cur2 := CurrentCursor;
END IF;
CurrentCursor:= InitCursor;
END; -
Oracle Forms6i
Hai All
While i am executing my cursor i got this error
This is my code
declare
in_time varchar2(25);
out_time varchar2(25);
intrin_time varchar2(25);
introut_time varchar2(25);
cursor test_cur is
select * from dail_att order by barcode;
begin
go_block('TEST_SRI');
first_record;
open test_cur;
loop
select intime,outtime,intrtimein,introuttime into in_time,out_time,intrin_time,introut_time from dail_att;
message('hai');
if :barcode is not null and in_time is not null then
update dail_att set outtime = :bartime where
barcode= :barcode and ATTEND_DATE = :bardate-1;
elsif :barcode is null then
insert into dail_att(barcode,intime,attend_date)
values(:barcode,:bartime,:bardate);
elsif :barcode is not null then
update dail_att set outtime = :bartime where
barcode= :barcode and ATTEND_DATE = :bardate;
elsif :barcode is not null and :bartime > in_time
and :bartime < out_time then
insert into dail_att
(barcode,intrtimein,attend_date)
values(:barcode,:bartime,:bardate);
elsif :barcode is not null and :bartime > in_time
and :bartime < out_time and :bartime > intrin_time then
update dail_att set introuttime = :bartime where
barcode= :barcode and ATTEND_DATE = :bardate;
end if;
EXIT WHEN :SYSTEM.LAST_RECORD = 'TRUE' OR :BARCODE IS NULL;
NEXT_RECORD;
END LOOP;
message('hai');
forms_ddl('commit');
exception
when others then
--forms_ddl('rollback');
message(sqlerrm||dbms_error_Text);
message(sqlerrm||dbms_error_Text);
End;
The Error is
ORA-01403 no data found ORA-00000 normal, success compailation
tell me how to solve this problem
Thanks & Regards
Srikkanth.MSrikanth,
First print the cursor value using message.
or write
begin
exception
end
for the query the following
select intime,outtime,intrtimein,introuttime into in_time,out_time,intrin_time,introut_time from dail_att;
kanish -
How to get rowtype of a ref cursor?
Hello again,
I need your help once more.
I have a function in a package which returns a SYS_REFCURSOR. Now I am trying to open that cursor from the application (currently sql_developer) to show the data. For starting I have a simple query in the statement: select * from emp;
Later it will be a complex query which returns results of multiple joined tables.
I have the following package:
>
CREATE OR REPLACE
PACKAGE P_TEST_ASP AS
FUNCTION test_asp_1 (dti_id in NUMBER)
RETURN SYS_REFCURSOR;
END P_TEST_ASP;
>
And here comes the package body:
>
CREATE OR REPLACE
PACKAGE BODY P_TEST_ASP AS
FUNCTION test_asp_1 (dti_id in NUMBER)
RETURN SYS_REFCURSOR AS
resultCursor SYS_REFCURSOR;
BEGIN
OPEN resultCursor FOR select * from emp;
RETURN resultCursor;
END test_asp_1;
END P_TEST_ASP;
>
Now my Problem is that I do not know how to get the cursor's rowtype to assign it to the collection:
I Managed to access the cursor when I set the rowtype of my collection res to emp%rowtype.
>
set serveroutput on
DECLARE
type testtype is TABLE OF emp%rowtype;
myCursor SYS_REFCURSOR;
res testtype;
BEGIN
-- Get ref cursor from function
myCursor := p_test_asp.test_asp_1(9);
FETCH myCursor BULK COLLECT into res;
dbms_output.put_line('Value from cursor:' );
CLOSE myCursor;
END;
>
But that will not work with the final statement.
I would like to set the rowtype to myCursor%rowtype -> But I don't know how to do it:
>
set serveroutput on
DECLARE
type testtype is TABLE OF myCursor%rowtype;
myCursor SYS_REFCURSOR;
res testtype;
BEGIN
-- Get ref cursor from function
myCursor := p_test_asp.test_asp_1(9);
FETCH myCursor BULK COLLECT into res;
dbms_output.put_line('Value from cursor:' );
CLOSE myCursor;
END;
>
this statement throws the following errors:
Fehlerbericht:
ORA-06550: line 2, column 36:
PLS-00320: the declaration of the type of this expression is incomplete or malformed
ORA-06550: line 2, column 3:
PL/SQL: Item ignored
ORA-06550: line 11, column 36:
PLS-00597: expression 'RES' in the INTO list is of wrong type
ORA-06550: line 11, column 3:
PL/SQL: SQL Statement ignored
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
Edited by: Andreas S. on 13.12.2011 04:56Why do you want to use a collection? I dont see any need for that.
Lets say your client is SQL Plus. SQL Plus provides a API called PRINT that prints the cursor. You can use that.
SQL> var rc refcursor
SQL>
SQL> exec open :rc for select level from dual connect by level <= 10;
PL/SQL procedure successfully completed.
SQL> print rc
LEVEL
1
2
3
4
5
6
7
8
9
10
10 rows selected.
SQL>Like wise whatever is your client use the correct API that offers to handle cursors. -
hi all,
can anyone let me know how to print alv line graph .
wat i want is print option in zcopy of pgm GFW_PROG_PRES_SHOW_MULT.
regards
Avik NayakOn Thu, 11 May 2000 17:39:54 GMT, Steve Drake
wrote:
>Hello everyone. I have LabView printing an XY graph but it always
>wants to print in Portrait mode. I set the defaults of the printer to
>LandScape mode and still go a Portrait printout. Is there anyway
>to force LabView to print in LandScape mode? This will help the graph
>be more readable.
>
Hi, well after some playing around and touching things that I though
shouldn't make a difference I got it to print in Landscape mode. On
the VI's front panel menu File-Print I switched that to LandScape mode
and what do you know it printed the graph out in LandScape mode.
Now I want to manipulate the fonts on the graph. I have messed with
the cursors and I can put x axis lines
on the chart with a time value
but the text I'm putting up is small so I need a bigger font and I
need to get the text out of the graph itself.
Is there anyway to print the cursor titles vertical instead of
horizontal to the x axis. Thought I would ask anyway.
Thanks to anyone who already knew how to do this.
Regards,
Steve Drake -
Printing a Labview graph in LandScape mode ?
Hello everyone. I have LabView printing an XY graph but it always
wants to print in Portrait mode. I set the defaults of the printer to
LandScape mode and still go a Portrait printout. Is there anyway
to force LabView to print in LandScape mode? This will help the graph
be more readable.
Thanks for any help you can give.
Regards,
Steve DrakeOn Thu, 11 May 2000 17:39:54 GMT, Steve Drake
wrote:
>Hello everyone. I have LabView printing an XY graph but it always
>wants to print in Portrait mode. I set the defaults of the printer to
>LandScape mode and still go a Portrait printout. Is there anyway
>to force LabView to print in LandScape mode? This will help the graph
>be more readable.
>
Hi, well after some playing around and touching things that I though
shouldn't make a difference I got it to print in Landscape mode. On
the VI's front panel menu File-Print I switched that to LandScape mode
and what do you know it printed the graph out in LandScape mode.
Now I want to manipulate the fonts on the graph. I have messed with
the cursors and I can put x axis lines
on the chart with a time value
but the text I'm putting up is small so I need a bigger font and I
need to get the text out of the graph itself.
Is there anyway to print the cursor titles vertical instead of
horizontal to the x axis. Thought I would ask anyway.
Thanks to anyone who already knew how to do this.
Regards,
Steve Drake -
Hi when i try to print a printable with an image on it , it keeps rendering the page it comes 170 time into the paintroutine , its this possible to it in an other way???
Greetings SvenSure when i can the print routine below of the panel (= report to be printed) the paint routine is called twice when sending it to the printer but when adding an image to the panel and the print , the paint routine is called 170 times or more
here is the printroutine called from the printpreview
void printButton_actionPerformed(ActionEvent e) {
try {
PrinterJob prnJob = PrinterJob.getPrinterJob();
PageFormat pf = prnJob.defaultPage();
pf.setPaper(paper);
if (jobType == PRINTABLE_JOB)
prnJob.setPrintable(m_printable,pf);
else
prnJob.setPageable(m_pageable);
setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
if (prnJob.printDialog())
prnJob.setJobName("Vrex Explorer printing");
prnJob.print();
setCursor( Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
dispose();
catch (PrinterException ex)
ex.printStackTrace();
System.err.println("Printing error:");
the printable is below
public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
if (pageIndex >= m_maxNumPage)
return Printable.NO_SUCH_PAGE;
else
Graphics2D g2 = (Graphics2D) g;
// RepaintManager.currentManager(this).setDoubleBufferingEnabled(false);
setDoubleBuffered(false);
paint(g2);
// RepaintManager.currentManager(this).setDoubleBufferingEnabled(true);
setDoubleBuffered(true);
System.gc();
return Printable.PAGE_EXISTS;
public void paint(Graphics2D g)
paintBackground(g);
private void paintBackground(Graphics2D g)
g.setColor(new Color(210,212,215));
int width = (int)pf.getImageableWidth();
int height =(int) pf.getImageableHeight()-getPoints(0.5);
int x = (int) pf.getImageableX();
int y = (int) pf.getImageableY();
// vertical shadowbalk
g.fillRect(x,y,(int)width/2,height);
g.setColor(new Color(15,40,70));
g.fillRect(x,y+getPoints(1.5),width,getPoints(1.5));
g.setFont(tfnt);
int titelorigin = getPoints(0.5);
fm = g.getFontMetrics(g.getFont());
int h = fm.getHeight();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(103,127,156));
g.drawString("DESIGN",x+titelorigin,y+getPoints(0.75)+(fm.getAscent()- fm.getDescent())/2);
fm = g.getFontMetrics(g.getFont());
h = fm.getHeight();
g.setColor(new Color(166,169,175));
g.drawString("OPPORTUNITIES",x+titelorigin,y+getPoints(2.25)+(fm.getAscent()- fm.getDescent())/2);
g.setColor(new Color(255,255,255));
g.setFont(t2fnt);
fm = g.getFontMetrics(g.getFont());
h = fm.getHeight();
g.drawString("DFA",x+titelorigin+width/4,y+height- getPoints(0.5)- (fm.getAscent()- fm.getDescent())/2);
try{
System.out.println("imageheight"+imageheight);
// g.drawImage(image,x+titelorigin,y+height -getPoints(0.5)-imageheight,imagewidth,imageheight,null);
catch( Exception ex)
with the g.drawimage ----->>> line enabled the paint is called 170 times
the image is constructed in the constructor of the page
like this
try
imagewidth = image.getWidth(this);
imageheight = image.getHeight(this);
MediaTracker mt = new MediaTracker(this);
mt.addImage(image,0);
mt.waitForID(0);
catch (Exception e)
e.printStackTrace();
tia Sven -
Print - JTable with a TITLE on each page
Hi! someone know haw can I print a MY TITLE on each page that I print ?
----->MY TITLE<----
| co1 | col2 | col3 | col4 |
|dtxxz|dtxyz|dtxyz|dtxyz|
|dtxxz|dtxyz|dtxyz|dtxyz|
|dtxxz|dtxyz|dtxyz|dtxyz|
PAGE 1
I try that :
g.drawString("MY TITLE", 100,50);
but the table header hide (writing over) my title
Here is my call :
public int print(Graphics g, PageFormat pageFormat, int pageIndex)
throws PrinterException {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
int fontHeight = g2.getFontMetrics().getHeight();
int fontDesent = g2.getFontMetrics().getDescent();
pageFormat.setOrientation(pageFormat.LANDSCAPE);
//leave room for page number
double pageHeight = pageFormat.getImageableHeight() - fontHeight;
double pageWidth = pageFormat.getImageableWidth();
double tableWidth =
(double) getCurrentTable().getColumnModel().getTotalColumnWidth();
double scale = 1;
if (tableWidth >= pageWidth) {
scale = pageWidth / tableWidth;
double headerHeightOnPage =
getCurrentTable().getTableHeader().getHeight() * scale ;
double tableWidthOnPage = tableWidth * scale;
double oneRowHeight =
(getCurrentTable().getRowHeight() + getCurrentTable().getRowMargin()) * scale;
int numRowsOnAPage = (int) ((pageHeight - headerHeightOnPage) / oneRowHeight);
double pageHeightForTable = oneRowHeight * numRowsOnAPage;
int totalNumPages =
(int) Math.ceil(((double) getCurrentTable().getRowCount()) / numRowsOnAPage);
if (pageIndex >= totalNumPages) {
return NO_SUCH_PAGE;
g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2.drawString(
"Page: " + (pageIndex + 1),
(int) pageWidth / 2 - 35,
(int) (pageHeight + fontHeight - fontDesent));
//bottom center
g2.translate(0f, headerHeightOnPage);
g2.translate(0f, -pageIndex * pageHeightForTable);
//TODO this next line treats the last page as a full page
g2.setClip(
0,
(int) (pageHeightForTable * pageIndex),
(int) Math.ceil(tableWidthOnPage),
(int) Math.ceil(pageHeightForTable));
g2.scale(scale, scale);
getCurrentTable().paint(g2);
g2.scale(1 / scale, 1 / scale);
g2.translate(0f, pageIndex * pageHeightForTable);
g2.translate(0f, -headerHeightOnPage);
g2.setClip(
0,
0,
(int) Math.ceil(tableWidthOnPage),
(int) Math.ceil(headerHeightOnPage));
g2.scale(scale, scale);
getCurrentTable().getTableHeader().paint(g2); //paint header at top
return Printable.PAGE_EXISTS;
Thanks//Solution-------------------------------------------------------------------------------------------------------
// PRINT : CENTER HEADER TITLE ON EACH PAGE
: PAGE NUMBER ON EACH PAGE
: USE A PREVIEW WINDOW
import javax.swing.*;
import javax.swing.table.*;
import java.awt.print.*;
import java.awt.*;
import java.awt.event.*;
* File: PrintTable.java
* (C) Copyright Corp. 2001 - All Rights Reserved.
* Print a JTable data
public class PrintTable implements Printable {
* Insert the method's description here.
* Creation date: (03-13-2002 13:50:41)
* @param g java.awt.Graphics
* @param pg java.awt.print.PageFormat
* @param i int
public int print(Graphics g, PageFormat pageFormat,
int pageIndex) throws PrinterException {
try{
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
int fontHeight = g2.getFontMetrics().getHeight();
int fontDesent = g2.getFontMetrics().getDescent();
// Normalize the header color
// he title of the report is not printed if the color of the header is different of these colors
m_table.getTableHeader().setBackground(new java.awt.Color(204,204,204));
m_table.getTableHeader().setForeground(new java.awt.Color(0,0,0));
//leave room for page number
double pageHeight = pageFormat.getImageableHeight() - fontHeight;
double pageWidth = pageFormat.getImageableWidth();
double tableWidth = (double) m_table.getColumnModel().getTotalColumnWidth();
double scale = 1;
if (tableWidth >= pageWidth) {
scale = pageWidth / tableWidth;
// Get the size of the table header
double headerHeightOnPage = m_table.getTableHeader().getHeight() * scale;
// Get the table size on a page
double tableWidthOnPage = tableWidth * scale;
// Title Height
double titleHeightOnPage = 0;
if( m_title != null ){
titleHeightOnPage = ((double)m_title.getFontMetrics(m_title.getFont()).getHeight() + 40) * scale;
// Get size of a row
double oneRowHeight =
(m_table.getRowHeight() + m_table.getRowMargin()) * scale;
int numRowsOnAPage = (int) ((pageHeight - headerHeightOnPage - titleHeightOnPage) / oneRowHeight);
// Get number of row in a page
double pageHeightForTable = oneRowHeight * numRowsOnAPage;
// Get the number of page to print
int totalNumPages =
(int) Math.ceil(((double) m_table.getRowCount()) / numRowsOnAPage);
if (pageIndex >= totalNumPages) {
return NO_SUCH_PAGE;
// Print the page label at bottom center
g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2.drawString(
"Page: " + (pageIndex + 1),
(int) pageWidth / 2 - 35,
(int) (pageHeight + fontHeight - fontDesent));
g2.translate(0f, headerHeightOnPage + titleHeightOnPage);
g2.translate(0f, -pageIndex * pageHeightForTable);
//If this piece of the table is smaller than the size available,
//clip to the appropriate bounds.
if (pageIndex + 1 == totalNumPages) {
int lastRowPrinted = numRowsOnAPage * pageIndex;
int numRowsLeft = m_table.getRowCount() - lastRowPrinted;
g2.setClip(
0,
(int) (pageHeightForTable * pageIndex),
(int) Math.ceil(tableWidthOnPage),
(int) Math.ceil(oneRowHeight * numRowsLeft));
//else clip to the entire area available.
else {
g2.setClip(
0,
(int) (pageHeightForTable * pageIndex),
(int) Math.ceil(tableWidthOnPage),
(int) Math.ceil(pageHeightForTable));
g2.scale(scale, scale);
m_table.paint(g2);
g2.scale(1 / scale, 1 / scale);
g2.translate(0f, pageIndex * pageHeightForTable);
g2.translate(0f, -headerHeightOnPage );
g2.setClip(
0,
0,
(int) Math.ceil(tableWidthOnPage),
(int) Math.ceil(headerHeightOnPage));
g2.scale(scale, scale);
// Paint header at the top of the page
m_table.getTableHeader().paint(g2);
g2.scale(1 / scale, 1/ scale);
g2.translate(0f, -titleHeightOnPage);
g2.setClip(
0,
0,
(int) Math.ceil(tableWidthOnPage),
(int) Math.ceil(titleHeightOnPage));
// Paint title
if( m_strTitle != null ){
//Center
g2.translate((pageFormat.getImageableWidth() / 2) -
(m_title.getFontMetrics(m_title.getFont()).stringWidth(m_title.getText()) / 2 ),
0f );
g2.drawString(m_title.getText(), 0, 10);
}else if ( m_title != null ){
//Center
g2.translate((pageFormat.getImageableWidth() / 2) -
(m_title.getFontMetrics(m_title.getFont()).stringWidth(m_title.getText()) / 2 ),
0f );
m_title.paint(g2);
}catch (Exception e){
e.printStackTrace();
return Printable.PAGE_EXISTS;
* Show a print dialog box
* Call the method to print
* @param JTable table : table to print
* @param String title : title of the table
public static void print(JTable table, String title) {
try {
m_table = table;
m_strTitle = title;
m_data = m_table.getModel();
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(PrintTable.instance, prnJob.defaultPage());
// if the print job is cancelled
if (!prnJob.printDialog())
return;
// print the table
prnJob.print();
} catch (PrinterException pe) {
pe.printStackTrace();
System.err.println("Printing error: " + pe.toString());
protected static PrintTable instance = new PrintTable();
public static int LANDSCAPE = PageFormat.LANDSCAPE;
protected static TableModel m_data;
protected static int m_maxNumPage = 1;
protected static String m_strTitle = null;
protected static JTable m_table;
protected static JLabel m_title = null;
// Paper orientation
public static int PORTRAIT = PageFormat.PORTRAIT;
private final static String PREVIEW_LBL = "Aper�u avant impression...";
* Insert the method's description here.
* Creation date: (03-13-2002 10:12:41)
public static void preview(JTable table) {
m_table = table;
m_data = table.getModel();
PrinterJob prnJob = PrinterJob.getPrinterJob();
new PrintPreview(PrintTable.instance,
PREVIEW_LBL,
prnJob.defaultPage());
* Insert the method's description here.
* Creation date: (03-13-2002 10:12:41)
public static void preview(JTable table, PageFormat pf) {
m_table = table;
m_data = table.getModel();
new PrintPreview(PrintTable.instance,
PREVIEW_LBL,
pf);
* Insert the method's description here.
* Creation date: (03-13-2002 10:12:41)
public static void preview(JTable table, String title) {
m_table = table;
m_data = table.getModel();
m_strTitle = title;
m_title = new JLabel(title);
PrinterJob prnJob = PrinterJob.getPrinterJob();
new PrintPreview(PrintTable.instance,
PREVIEW_LBL,
prnJob.defaultPage());
* Insert the method's description here.
* Creation date: (03-13-2002 10:12:41)
public static void preview(JTable table, String title, PageFormat pf) {
m_table = table;
m_data = table.getModel();
m_strTitle = title;
m_title = new JLabel(title);
new PrintPreview(PrintTable.instance,
PREVIEW_LBL,
pf);
* Insert the method's description here.
* Creation date: (03-13-2002 10:12:41)
public static void preview(JTable table, JLabel title) {
m_table = table;
m_data = table.getModel();
m_title = title;
PrinterJob prnJob = PrinterJob.getPrinterJob();
new PrintPreview(PrintTable.instance,
PREVIEW_LBL,
prnJob.defaultPage());
* Insert the method's description here.
* Creation date: (03-13-2002 10:12:41)
public static void preview(JTable table, JLabel title, PageFormat pf) {
m_table = table;
m_data = table.getModel();
m_title = title;
new PrintPreview(PrintTable.instance,
PREVIEW_LBL,
pf);
* Show a print dialog box
* Call the method to print
* @param JTable table : table to print
* @param String title : title of the table
public static void print(JTable table, String title, PageFormat pf) {
try {
m_table = table;
m_strTitle = title;
m_data = m_table.getModel();
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(PrintTable.instance, pf);
// if the print job is cancelled
if (!prnJob.printDialog())
return;
// print the table
prnJob.print();
} catch (PrinterException pe) {
pe.printStackTrace();
System.err.println("Printing error: " + pe.toString());
* Show a print dialog box
* Call the method to print
* @param JTable table : table to print
* @param String title : title of the table
public static void print(JTable table, String title, PageFormat pf, int orientation) {
try {
m_table = table;
m_strTitle = title;
m_data = m_table.getModel();
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(PrintTable.instance, prnJob.defaultPage());
pf.setOrientation(orientation);
// if the print job is cancelled
if (!prnJob.printDialog())
return;
// print the table
prnJob.print();
} catch (PrinterException pe) {
pe.printStackTrace();
System.err.println("Printing error: " + pe.toString());
* Show a print dialog box
* Call the method to print
* @param JTable table : table to print
* @param String title : title of the table
public static void print(JTable table, JLabel title) {
try {
m_table = table;
m_title = title;
m_data = table.getModel();
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(PrintTable.instance, prnJob.defaultPage());
// if the print job is cancelled
if (!prnJob.printDialog())
return;
// print the table
prnJob.print();
} catch (PrinterException pe) {
pe.printStackTrace();
System.err.println("Printing error: " + pe.toString());
* Show a print dialog box
* Call the method to print
* @param JTable table : table to print
* @param String title : title of the table
public static void print(JTable table, JLabel title, PageFormat pf) {
try {
m_table = table;
m_title = title;
m_data = table.getModel();
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(PrintTable.instance, pf);
// if the print job is cancelled
if (!prnJob.printDialog())
return;
// print the table
prnJob.print();
} catch (PrinterException pe) {
pe.printStackTrace();
System.err.println("Printing error: " + pe.toString());
* Show a print dialog box
* Call the method to print
* @param JTable table : table to print
* @param String title : title of the table
public static void print(JTable table, JLabel title, PageFormat pf, int orientation) {
try {
m_table = table;
m_title = title;
m_data = table.getModel();
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(PrintTable.instance, pf);
// if the print job is cancelled
if (!prnJob.printDialog())
return;
pf.setOrientation(orientation);
// print the table
prnJob.print();
} catch (PrinterException pe) {
pe.printStackTrace();
System.err.println("Printing error: " + pe.toString());
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import java.awt.print.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class PrintPreview extends JFrame
protected int m_wPage;
protected int m_hPage;
protected Printable m_target;
protected JComboBox m_cbScale;
protected PreviewContainer m_preview;
private String lblBtnClose = "Fermer";
private String lblBtnPrint = "Imprimer...";
protected PageFormat m_pf;
private String[] scales = { "10 %", "25 %", "50 %", "100 %" };
public PrintPreview(Printable target, String title, PageFormat pf) {
super(title);
setSize(600, 400);
m_target = target;
m_pf = pf;
JToolBar tb = new JToolBar();
JButton bt = new JButton(this.lblBtnPrint);
ActionListener lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// Use default printer, no dialog
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(m_target, m_pf);
setCursor( Cursor.getPredefinedCursor(
Cursor.WAIT_CURSOR));
prnJob.print();
setCursor( Cursor.getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
dispose();
catch (PrinterException ex) {
ex.printStackTrace();
System.err.println("Printing error: "+ex.toString());
bt.addActionListener(lst);
bt.setAlignmentY(0.5f);
bt.setMargin(new Insets(4,6,4,6));
tb.add(bt);
bt = new JButton(this.lblBtnClose);
lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
bt.addActionListener(lst);
bt.setAlignmentY(0.5f);
bt.setMargin(new Insets(2,6,2,6));
tb.add(bt);
m_cbScale = new JComboBox(scales);
lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread runner = new Thread() {
public void run() {
String str = m_cbScale.getSelectedItem().
toString();
if (str.endsWith("%"))
str = str.substring(0, str.length()-1);
str = str.trim();
int scale = 0;
try { scale = Integer.parseInt(str); }
catch (NumberFormatException ex) { return; }
int w = (int)(m_wPage*scale/100);
int h = (int)(m_hPage*scale/100);
Component[] comps = m_preview.getComponents();
for (int k=0; k<comps.length; k++) {
if (!(comps[k] instanceof PagePreview))
continue;
PagePreview pp = (PagePreview)comps[k];
pp.setScaledSize(w, h);
m_preview.doLayout();
m_preview.getParent().getParent().validate();
runner.start();
m_cbScale.addActionListener(lst);
m_cbScale.setMaximumSize(m_cbScale.getPreferredSize());
m_cbScale.setEditable(true);
tb.addSeparator();
tb.add(m_cbScale);
getContentPane().add(tb, BorderLayout.NORTH);
m_preview = new PreviewContainer();
PrinterJob prnJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = pf;
if (pageFormat.getHeight()==0 || pageFormat.getWidth()==0) {
System.err.println("Unable to determine default page size");
return;
m_wPage = (int)(pageFormat.getWidth());
m_hPage = (int)(pageFormat.getHeight());
int scale = 10;
int w = (int)(m_wPage*scale/100);
int h = (int)(m_hPage*scale/100);
int pageIndex = 0;
try {
while (true) {
BufferedImage img = new BufferedImage(m_wPage,
m_hPage, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, m_wPage, m_hPage);
if (target.print(g, pageFormat, pageIndex) !=
Printable.PAGE_EXISTS)
break;
PagePreview pp = new PagePreview(w, h, img);
m_preview.add(pp);
pageIndex++;
catch (PrinterException e) {
e.printStackTrace();
System.err.println("Printing error: "+e.toString());
JScrollPane ps = new JScrollPane(m_preview);
getContentPane().add(ps, BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
* Insert the type's description here.
* Creation date: (03-12-2002 14:17:45)
* @author: Alexandre Spain
public class PreviewContainer extends JPanel {
protected int H_GAP = 16;
protected int V_GAP = 10;
* PreviewContainer constructor comment.
public PreviewContainer() {
super();
public void doLayout() {
Insets ins = getInsets();
int x = ins.left + H_GAP;
int y = ins.top + V_GAP;
int n = getComponentCount();
if (n == 0)
return;
Component comp = getComponent(0);
Dimension dc = comp.getPreferredSize();
int w = dc.width;
int h = dc.height;
Dimension dp = getParent().getSize();
int nCol = Math.max((dp.width-H_GAP)/(w+H_GAP), 1);
int nRow = n/nCol;
if (nRow*nCol < n)
nRow++;
int index = 0;
for (int k = 0; k<nRow; k++) {
for (int m = 0; m<nCol; m++) {
if (index >= n)
return;
comp = getComponent(index++);
comp.setBounds(x, y, w, h);
x += w+H_GAP;
y += h+V_GAP;
x = ins.left + H_GAP;
public Dimension getMaximumSize() {
return getPreferredSize();
public Dimension getMinimumSize() {
return getPreferredSize();
public Dimension getPreferredSize() {
int n = getComponentCount();
if (n == 0)
return new Dimension(H_GAP, V_GAP);
Component comp = getComponent(0);
Dimension dc = comp.getPreferredSize();
int w = dc.width;
int h = dc.height;
Dimension dp = getParent().getSize();
int nCol = Math.max((dp.width-H_GAP)/(w+H_GAP), 1);
int nRow = n/nCol;
if (nRow*nCol < n)
nRow++;
int ww = nCol*(w+H_GAP) + H_GAP;
int hh = nRow*(h+V_GAP) + V_GAP;
Insets ins = getInsets();
return new Dimension(ww+ins.left+ins.right,
hh+ins.top+ins.bottom);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
* Insert the type's description here.
* Creation date: (03-12-2002 14:17:06)
* @author: Alexandre Spain
public class PagePreview extends JPanel {
protected int m_w;
protected int m_h;
protected Image m_source;
protected Image m_img;
* PagePreview constructor comment.
* @param target java.awt.print.Printable
public PagePreview(int w, int h, Image source) {
m_w = w;
m_h = h;
m_source= source;
m_img = m_source.getScaledInstance(m_w, m_h,
Image.SCALE_SMOOTH);
m_img.flush();
setBackground(Color.white);
setBorder(new MatteBorder(1, 1, 2, 2, Color.black));
public Dimension getMaximumSize() {
return getPreferredSize();
public Dimension getMinimumSize() {
return getPreferredSize();
public Dimension getPreferredSize() {
Insets ins = getInsets();
return new Dimension(m_w+ins.left+ins.right,
m_h+ins.top+ins.bottom);
public void paint(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(m_img, 0, 0, this);
paintBorder(g);
public void setScaledSize(int w, int h) {
m_w = w;
m_h = h;
m_img = m_source.getScaledInstance(m_w, m_h,
Image.SCALE_SMOOTH);
repaint(); -
Hi , Iknow... this is an question very request... but... What can say . I NEED HEL P
I need printing JTABLE LANDSCAPE here my code example ...
Thank you.
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import com.sun.java.swing.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.OrientationRequested;
import javax.swing.*;
public class printpanel extends JPanel implements ActionListener, Printable {
public printpanel() {
setBackground(Color.white);
JButton b = new JButton("MyButton");
b.addActionListener(this);
add(b);
JLabel tit = new JLabel ("Liquidaci�n M�dico");
tit.setFont( new Font( "Helvetica",Font.BOLD,16 ) );
tit.setForeground(Color.black);
setBackground(Color.white);
add(tit);
//array bidimencional de objetos con los datos de la tabla
final Object[][] data = {
{"Mary", "Campione", "Esquiar", new Integer(5), new Boolean(false)},
{"Lhucas", "Huml", "Patinar", new Integer(3), new Boolean(true)},
{"Kathya", "Walrath", "Escalar", new Integer(2), new Boolean(false)},
{"Marcus", "Andrews", "Correr", new Integer(7), new Boolean(true)},
{"Angela", "Lalth", "Nadar", new Integer(4), new Boolean(false)}
//array de String's con los t�tulos de las columnas
final String[] columnNames = {"Nombre", "Apellido", "Pasatiempo",
"A�os de Practica", "Soltero(a)"};
//se crea la Tabla
final JTable table = new JTable(data, columnNames);
// table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setSelectionBackground( Color.red );
//Creamos un JscrollPane y le agregamos la JTable
final JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
public void actionPerformed(ActionEvent e) {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
PageFormat a = new PageFormat();
try { printJob.print(); } catch (Exception PrintException) { }
public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
if (pi >= 1) {
return Printable.NO_SUCH_PAGE;
Graphics2D g2d= (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
Font f = new Font("Monospaced",Font.PLAIN,12);
g2d.setFont (f);
paint (g);
return Printable.PAGE_EXISTS;
public static void main(String s[]) {
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
Frame f = new Frame("Imprimir");
f.addWindowListener(l);
f.add("Center", new printpanel());
//f.pack();
f.setSize(new Dimension(500,300));
f.show();
}Hai!,
I am posting this code for the request i received from the mfwjava-person by mail. The below modified code works well.
I Used ORACLE ODBC* since it only supports more query features of sql statements and your select *... statement works well in this only. I didn't checked the print - out. But our senior Mr.URHAND checked it(Thank him).
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.print.attribute.*;
import javax.print.*;
import javax.print.attribute.standard.*;
import javax.print.attribute.standard.MediaSize;
import java.sql.Connection;
import java.sql.*;
import java.text.MessageFormat;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
public class Grafica extends JPanel implements ActionListener {
JTable table=new JTable();
public static JScrollPane scrollPane;
public Grafica() {
JButton b = new JButton("Imprimir");
b.addActionListener(this);
add(b);
JLabel tit = new JLabel("Liquidaci�n M�dico");
tit.setFont( new Font( "Helvetica",Font.BOLD,16 ) );
tit.setForeground(Color.black);
setBackground(Color.white);
add(tit);
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Sego", "scott", "tiger");
DriverManager.setLogStream(System.out);
Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rs = statement.executeQuery("SELECT Medico_opera,Descip_Item,Codigo_estudio,Count(Descip_Item),Sum(Liquid_opera) FROM Datos Group By Medico_opera,Descip_Item,Codigo_estudio ");
rs=statement.getResultSet();
String[] columnas = {"M�dico","Descripci�n Item","Codigo nr.","Total de Items","Total M�dico Op."};
JTable table =rsInTable(rs);
scrollPane = new JScrollPane(table);
add(scrollPane);
statement.close();
con.close();
} catch (SQLException sqle) {
sqle.printStackTrace();
} catch (Exception ed) {
ed.printStackTrace();
public void actionPerformed(ActionEvent e) {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable( new TableReport(table,
new MessageFormat("Liquidaci�n M�dico"), null) );
try{
PrinterJob prnJob = PrinterJob.getPrinterJob();
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
//aset.add(new Copies(2));
//aset.add(new MediaSize.getMediaSizeForName(MediaSizeName.ISO_A4));
//aset.add(MediaName.ISO_A4_WHITE);
aset.add(MediaSizeName.ISO_A4);
aset.add(Sides.ONE_SIDED);
aset.add(OrientationRequested.LANDSCAPE);//------>HERE IT IS
if (!prnJob.printDialog(aset))return;
//aset.add(MediaName.ISO_A4_TRANSPARENT);
setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
prnJob.print();
setCursor( Cursor.getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
}catch (Exception PrintException) {}
public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
if (pi >= 1) {
return Printable.NO_SUCH_PAGE;
Graphics2D g2d= (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
Font f = new Font("Monospaced",Font.PLAIN,12);
g2d.setFont(f);
paint(g);
return Printable.PAGE_EXISTS;
public static void main(String s[]) {
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
Frame f = new Frame("Imprimir");
f.addWindowListener(l);
f.add("Center", new Grafica());
f.setSize(new Dimension(500,300));
f.show();
public JTable rsInTable(ResultSet rs)throws SQLException{
JTable table;
boolean moreRecords=rs.next();
table=new JTable(0,0);
Vector colh=new Vector();
Vector rows=new Vector();
try{
ResultSetMetaData rsmd=rs.getMetaData();
for(int i=1;i<=rsmd.getColumnCount();++i)
colh.addElement(rsmd.getColumnName(i));
System.out.println(String.valueOf(rs.getRow()));
while(rs.next()){
rows.addElement(getNextRow(rs,rsmd));
table=new JTable(rows,colh);
catch(SQLException e2)
e2.printStackTrace();
if(!moreRecords)
return table;
return table;
private Vector getNextRow(ResultSet rs,ResultSetMetaData rsmd)throws SQLException
Vector crow=new Vector();
for(int i=1;i<=rsmd.getColumnCount();++i)
switch(rsmd.getColumnType(i))
case Types.VARCHAR:
crow.addElement(rs.getString(i));
break;
case Types.INTEGER:
crow.addElement(new Long(rs.getLong(i)));
break;
case Types.DOUBLE:
crow.addElement(new Double(rs.getDouble(i)));
break;//----> HERE U ADD OTHER TYPES - U NEED?
default:
crow.addElement(new String(rs.getString(i)));
System.out.println("type was: "+rsmd.getColumnTypeName(i));
break;
return crow;
class TableReport implements Printable {
private JTable table;
private JTableHeader header;
private TableColumnModel colModel;
private int totalColWidth;
private MessageFormat headerFormat;
private MessageFormat footerFormat;
private int last = -1;
private int row = 0;
private int col = 0;
private final Rectangle clip = new Rectangle(0, 0, 0, 0);
private final Rectangle hclip = new Rectangle(0, 0, 0, 0);
private final Rectangle tempRect = new Rectangle(0, 0, 0, 0);
private static final int H_F_SPACE = 8;
private static final float HEADER_FONT_SIZE = 18.0f;
private static final float FOOTER_FONT_SIZE = 12.0f;
private Font headerFont;
private Font footerFont;
public TableReport(JTable table,
MessageFormat headerFormat,
MessageFormat footerFormat) {
this.table = table;
header = table.getTableHeader();
colModel = table.getColumnModel();
totalColWidth = colModel.getTotalColumnWidth();
if (header != null) {
hclip.height = header.getHeight();
this.headerFormat = headerFormat;
this.footerFormat = footerFormat;
headerFont = table.getFont().deriveFont(Font.BOLD,
HEADER_FONT_SIZE);
footerFont = table.getFont().deriveFont(Font.PLAIN,
FOOTER_FONT_SIZE);
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
final int imgWidth = (int)pageFormat.getImageableWidth();
final int imgHeight = (int)pageFormat.getImageableHeight();
if (imgWidth <= 0) {
throw new PrinterException("Width of printable area is too small.");
Object[] pageNumber = new Object[]{new Integer(pageIndex + 1)};
String headerText = null;
if (headerFormat != null) {
headerText = headerFormat.format(pageNumber);
String footerText = null;
if (footerFormat != null) {
footerText = footerFormat.format(pageNumber);
Rectangle2D hRect = null;
Rectangle2D fRect = null;
int headerTextSpace = 0;
int footerTextSpace = 0;
int availableSpace = imgHeight;
if (headerText != null) {
graphics.setFont(headerFont);
hRect = graphics.getFontMetrics().getStringBounds(headerText,
graphics);
headerTextSpace = (int)Math.ceil(hRect.getHeight());
availableSpace -= headerTextSpace + H_F_SPACE;
if (footerText != null) {
graphics.setFont(footerFont);
fRect = graphics.getFontMetrics().getStringBounds(footerText,
graphics);
footerTextSpace = (int)Math.ceil(fRect.getHeight());
availableSpace -= footerTextSpace + H_F_SPACE;
if (availableSpace <= 0) {
throw new PrinterException("Height of printable area is too small.");
double sf = 1.0D;
if ( totalColWidth > imgWidth) {
sf = (double)imgWidth / (double)totalColWidth;
while (last < pageIndex) {
if (row >= table.getRowCount() && col == 0) {
return NO_SUCH_PAGE;
int scaledWidth = (int)(imgWidth / sf);
int scaledHeight = (int)((availableSpace - hclip.height) / sf);
findNextClip(scaledWidth, scaledHeight);
last++;
Graphics2D g2d = (Graphics2D)graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
AffineTransform oldTrans;
if (footerText != null) {
oldTrans = g2d.getTransform();
g2d.translate(0, imgHeight - footerTextSpace);
printText(g2d, footerText, fRect, footerFont, imgWidth);
g2d.setTransform(oldTrans);
if (headerText != null) {
printText(g2d, headerText, hRect, headerFont, imgWidth);
g2d.translate(0, headerTextSpace + H_F_SPACE);
tempRect.x = 0;
tempRect.y = 0;
tempRect.width = imgWidth;
tempRect.height = availableSpace;
g2d.clip(tempRect);
if (sf != 1.0D) {
g2d.scale(sf, sf);
} else {
int diff = (imgWidth - clip.width) / 2;
g2d.translate(diff, 0);
oldTrans = g2d.getTransform();
Shape oldClip = g2d.getClip();
if (header != null) {
hclip.x = clip.x;
hclip.width = clip.width;
g2d.translate(-hclip.x, 0);
g2d.clip(hclip);
header.print(g2d);
g2d.setTransform(oldTrans);
g2d.setClip(oldClip);
g2d.translate(0, hclip.height);
g2d.translate(-clip.x, -clip.y);
g2d.clip(clip);
table.print(g2d);
g2d.setTransform(oldTrans);
g2d.setClip(oldClip);
g2d.setColor(Color.BLACK);
g2d.drawRect(0, 0, clip.width, hclip.height + clip.height);
return PAGE_EXISTS;
private void printText(Graphics2D g2d,
String text,
Rectangle2D rect,
Font font,
int imgWidth) {
int tx;
if (rect.getWidth() < imgWidth) {
tx = (int)((imgWidth - rect.getWidth()) / 2);
} else if (table.getComponentOrientation().isLeftToRight()) {
tx = 0;
} else {
tx = -(int)(Math.ceil(rect.getWidth()) - imgWidth);
int ty = (int)Math.ceil(Math.abs(rect.getY()));
g2d.setColor(Color.BLACK);
g2d.setFont(font);
g2d.drawString(text, tx, ty);
private void findNextClip(int pw, int ph) {
final boolean ltr = table.getComponentOrientation().isLeftToRight();
if (col == 0) {
if (ltr) {
clip.x = 0;
} else {
clip.x = totalColWidth;
clip.y += clip.height;
clip.width = 0;
clip.height = 0;
int rowCount = table.getRowCount();
int rowHeight = table.getRowHeight(row);
do {
clip.height += rowHeight;
if (++row >= rowCount) {
break;
rowHeight = table.getRowHeight(row);
} while (clip.height + rowHeight <= ph);
clip.x = 0;
clip.width = totalColWidth;
* ALWAYS POST IN THIS FORUMS
*I ALWAYS LIKE TO REPLY IN THIS FORUM.SO PLEASE!!!! -
Why can't I print from Photoshop?
When I click print, the cursor just spins. I have to manually shut the program down. I have already tried to uninstall and re-install it.
Which version of PSE?
Windows or Mac?
Are you attempting to print from Editor or from Organizer?
Is the printer set as the default printer?
Are the latest drivers installed for your printer?
Any error messages?
Can you print from other applications?
Is the printer connected via USB or are you on a network? -
PrintPreview for a GridControl ?
Hello guys,
I like to show a PrintPreview of a
GridControl. So user could see the style of
GridControl before printing.
I found a peace of code as a class that
we can instantiate it to view a printPreviw
of a "JTable". It works fine when I pass
JTable as a Printable job to the
my PrintPreview class.
That's a valuable code which every body can use it(I paste it below).
But I could not Print Preview a GridControl.
My question is "How can I use this peace of code to Print Preview a GridControl".
// Print Preview class for JTable
package Tree;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.print.*;
import javax.swing.border.*;
public class MyPrintPreview extends JFrame {
BorderLayout borderLayout1 = new BorderLayout();
JPanel jPanel1 = new JPanel();
protected int m_wPage;
protected int m_hPage;
protected Printable m_target;
protected JComboBox m_cbScale;
protected PreviewContainer m_preview;
public MyPrintPreview(Printable target) {
this(target, "Print Preview");
public MyPrintPreview(Printable target, String title) {
super(title);
setSize(600, 400);
m_target = target;
JToolBar tb = new JToolBar();
JButton bt = new JButton("Print", new ImageIcon("print.gif"));
ActionListener lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// Use default printer, no dialog
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(m_target);
setCursor( Cursor.getPredefinedCursor(
Cursor.WAIT_CURSOR));
prnJob.print();
setCursor( Cursor.getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
dispose();
catch (PrinterException ex) {
ex.printStackTrace();
System.err.println("Printing error: "+ex.toString());
bt.addActionListener(lst);
bt.setAlignmentY(0.5f);
bt.setMargin(new Insets(4,6,4,6));
tb.add(bt);
bt = new JButton("Close");
lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
bt.addActionListener(lst);
bt.setAlignmentY(0.5f);
bt.setMargin(new Insets(2,6,2,6));
tb.add(bt);
String[] scales = { "10 %", "25 %", "50 %", "100 %" };
m_cbScale = new JComboBox(scales);
lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread runner = new Thread() {
public void run() {
String str = m_cbScale.getSelectedItem().
toString();
if (str.endsWith("%"))
str = str.substring(0, str.length()-1);
str = str.trim();
int scale = 0;
try { scale = Integer.parseInt(str); }
catch (NumberFormatException ex) { return; }
int w = (int)(m_wPage*scale/100);
int h = (int)(m_hPage*scale/100);
Component[] comps = m_preview.getComponents();
for (int k=0; k<comps.length; k++) {
if (!(comps[k] instanceof PagePreview))
continue;
PagePreview pp = (PagePreview)comps[k];
pp.setScaledSize(w, h);
m_preview.doLayout();
m_preview.getParent().getParent().validate();
runner.start();
m_cbScale.addActionListener(lst);
m_cbScale.setMaximumSize(m_cbScale.getPreferredSize());
m_cbScale.setEditable(true);
tb.addSeparator();
tb.add(m_cbScale);
getContentPane().add(tb, BorderLayout.NORTH);
m_preview = new PreviewContainer();
PrinterJob prnJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = prnJob.defaultPage();
if (pageFormat.getHeight()==0 | | pageFormat.getWidth()==0) {
System.err.println("Unable to determine default page size");
return;
m_wPage = (int)(pageFormat.getWidth());
m_hPage = (int)(pageFormat.getHeight());
int scale = 10;
int w = (int)(m_wPage*scale/100);
int h = (int)(m_hPage*scale/100);
int pageIndex = 0;
try {
while (true) {
BufferedImage img = new BufferedImage(m_wPage,
m_hPage, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, m_wPage, m_hPage);
if (target.print(g, pageFormat, pageIndex) !=
Printable.PAGE_EXISTS)
break;
PagePreview pp = new PagePreview(w, h, img);
m_preview.add(pp);
pageIndex++;
ca tch (PrinterException e) {
e.printStackTrace();
System.err.println("Printing error: "+e.toString());
JScrollPane ps = new JScrollPane(m_preview);
getContentPane().add(ps, BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
class PreviewContainer extends JPanel
protected int H_GAP = 16;
protected int V_GAP = 10;
public Dimension getPreferredSize() {
int n = getComponentCount();
if (n == 0)
return new Dimension(H_GAP, V_GAP);
Component comp = getComponent(0);
Dimension dc = comp.getPreferredSize();
int w = dc.width;
int h = dc.height;
Dimension dp = getParent().getSize();
int nCol = Math.max((dp.width-H_GAP)/(w+H_GAP), 1);
int nRow = n/nCol;
if (nRow*nCol < n)
nRow++;
int ww = nCol*(w+H_GAP) + H_GAP;
int hh = nRow*(h+V_GAP) + V_GAP;
Insets ins = getInsets();
return new Dimension(ww+ins.left+ins.right,
hh+ins.top+ins.bottom);
public Dimension getMaximumSize() {
return getPreferredSize();
public Dimension getMinimumSize() {
return getPreferredSize();
public void doLayout() {
Insets ins = getInsets();
int x = ins.left + H_GAP;
int y = ins.top + V_GAP;
int n = getComponentCount();
if (n == 0)
return;
Component comp = getComponent(0);
Dimension dc = comp.getPreferredSize();
int w = dc.width;
int h = dc.height;
Dimension dp = getParent().getSize();
int nCol = Math.max((dp.width-H_GAP)/(w+H_GAP), 1);
int nRow = n/nCol;
if (nRow*nCol < n)
nRow++;
int index = 0;
for (int k = 0; k<nRow; k++) {
for (int m = 0; m<nCol; m++) {
if (index >= n)
return;
comp = getComponent(index++);
comp.setBounds(x, y, w, h);
x += w+H_GAP;
y += h+V_GAP;
x = ins.left + H_GAP;
class PagePreview extends JPanel
protected int m_w;
protected int m_h;
protected Image m_source;
protected Image m_img;
public PagePreview(int w, int h, Image source) {
m_w = w;
m_h = h;
m_source= source;
m_img = m_source.getScaledInstance(m_w, m_h,
Image.SCALE_SMOOTH);
m_img.flush();
setBackground(Color.white);
setBorder(new MatteBorder(1, 1, 2, 2, Color.black));
public void setScaledSize(int w, int h) {
m_w = w;
m_h = h;
m_img = m_source.getScaledInstance(m_w, m_h,
Image.SCALE_SMOOTH);
repaint();
public Dimension getPreferredSize() {
Insets ins = getInsets();
return new Dimension(m_w+ins.left+ins.right,
m_h+ins.top+ins.bottom);
public Dimension getMaximumSize() {
return getPreferredSize();
public Dimension getMinimumSize() {
return getPreferredSize();
public void paint(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(m_img, 0, 0, this);
paintBorder(g);
}// end of myPrintPreview class
// Add below code to your Applet/Application
// first add a item menu on your menu
MenuFilePrintPreview.setText("Print Preview");
MenuFile.add(MenuFilePrintPreview);
ActionListener lstPreview = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread runner = new Thread() {
public void run() {
setCursor(Cursor.getPredefinedCursor(
Cursor.WAIT_CURSOR));
try{
new MyPrintPreview(this ,"My Print Preview");
}catch(Exception e){
e.printStackTrace();
System.err.println("Printer Error: "+e.toString());
setCursor(Cursor.getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
runner.start();
MenuFilePrintPreview.addActionListener(lstPreview);
nullAli,
The piece you are missing is the code to get the JTable that is underlying your GridControl. You do this as follows:
JTable tableView = myGridControl.getTable();
Blaise
null -
Executing procedure with IN OUT parameters using SQL developer
Hi, I'm trying to exceute the below procedure in SQL developer. Here the IN OUT cursor 'journal_cursor' is already defined.
PROCEDURE LIST_FORPROJECT (
p_project_sid IN NUMBER,
p_journal_cursor IN OUT journal_cursor,
AS
BEGIN
OPEN p_journal_cursor FOR
-- get the journal
SELECT j.JOURNAL_KEY AS "Journal_SID",
j.JOURNALTEXT AS "Entry",
j.CREATEDATE AS "CreateDate",
--j.COMMENT_ AS "Comment",
j.PROJECTPHASETASK_KEY AS "ProjectPhaseTaskSet_SID",
j.person_key AS "Person_SID"
FROM vdl_JOURNAL j
INNER JOIN vdl_PROJECTJOURNAL pj ON pj.JOURNAL_KEY = j.JOURNAL_KEY
WHERE pj.PROJECT_KEY = p_project_sid
ORDER BY j.CREATEDATE ASC, j.JOURNAL_KEY ASC;
END LIST_FORPROJECT;
When trying to run the above procedure through SQL developer, I get the below code generated.
DECLARE
P_PROJECT_SID NUMBER;
P_JOURNAL_CURSOR journal_cursor;
BEGIN
P_PROJECT_SID := 5974;
-- Modify the code to initialize the variable
-- P_JOURNAL_CURSOR := NULL;
-- Modify the code to initialize the variable
LIST_FORPROJECT(
P_PROJECT_SID => P_PROJECT_SID,
P_JOURNAL_CURSOR => P_JOURNAL_CURSOR,
-- Modify the code to output the variable
DBMS_OUTPUT.PUT_LINE('P_JOURNAL_CURSOR' || P_JOURNAL_CURSOR);
END;
But executing the above sql doesn't print the cursor as output but errors out saying 'wrong number or type or arguments in call to ||'. Can somebody please help me in finding a way test and view the results of such a procedure through SQL developer?
Any help is highly appreciated.
Regards,
RanganathHi,
I was able to solve the problem.. My cursor was declared like this.
TYPE journal_def IS RECORD
journal_sid NUMBER(10),
journaltext CLOB,
createdate DATE,
projectphasetaskset_sid NUMBER(10),
person_sid NUMBER(10)
TYPE journal_cursor IS REF CURSOR RETURN journal_def;
I used the journal_def type to fetch the records.
Here is how my final sql looked like.
DECLARE
P_PROJECT_SID NUMBER;
P_JOURNAL_CURSOR journal_cursor;
P_J_CURSOR journal_def;
BEGIN
P_PROJECT_SID := 11171;
-- Modify the code to initialize the variable
-- P_JOURNAL_CURSOR := NULL;
LIST_FORPROJECT(
P_PROJECT_SID => P_PROJECT_SID,
P_JOURNAL_CURSOR => P_JOURNAL_CURSOR,
-- Modify the code to output the variable
BEGIN
--open P_JOURNAL_CURSOR;
loop
fetch P_JOURNAL_CURSOR into P_J_CURSOR;
exit when P_JOURNAL_CURSOR%NOTFOUND;
DBMS_OUTPUT.put_line(P_J_CURSOR.journal_sid);
end loop;
--close P_JOURNAL_CURSOR;
END;
END;
This gave me results. Thanks a ton ALL for your help..... :)..
Regards,
Ranganath -
Re: array of references to linked lists
Hi, im having a little problem seeing the wood from the tree...shouldnt be too hard for a fresh pair of eyes...ive been trying for a while now(read ages !!).
I have an array which will be populated with seperate linked lists (StudentList class) which are populated from a console interface (prompt).
It seems to work fine, however .. each list entered will overwrite the last by adding itself to it. eg :
list 1 is added : adam 998 albert 999
list 2 is added : john 123 jill 666
lists[0].print() : jill 666 john 123 albert 999 adam 998
lists[1].print() : jill 666 john 123 albert 999 adam 998
it should give
lists[0].print() : jill 666 john 123
lists[1].print() : albert 999 adam 998
the code is below,
cheers for ANY help,
ta.
import java.io.*;
import java.util.*;
public class StudentId {
public static void main(java.lang.String[] args) {
StudentList[] lists = new StudentList[20];
for (int i = 0; i < lists.length; i++) {
lists[i] = new StudentList();
int n = 0;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
for(;;) {
System.out.print("Please enter a student record list> ");
try {
//StudentList list = new StudentList();
String line = in.readLine();
if (line.equals("quit")) {
break;
StringTokenizer tokenBag = new StringTokenizer (line," ");
while (tokenBag.hasMoreTokens()) {
try {
String name = tokenBag.nextToken();
String idString = tokenBag.nextToken();
int id = Integer.parseInt(idString);
lists[n].insert(name, id);
catch(Exception e) {
System.out.println("Input error : " + e);
catch (Exception e) {
System.out.println("exception : " + e);
n += 1;
for (int i=0; i<n; i++) {
System.out.println("element " + i);
lists.print();other class (Int node class is standard node class altered
public class StudentList {
private static IntNode head;
private static int count;
public StudentList() {
head = null;
count = 0;
public boolean isEmpty() {
if (count == 0) return true;
else return false;
public int size(){
return count;
public IntNode getHead() {
return head;
public void printHead() {
System.out.println(head.getName() + " " + head.getId());
public IntNode getTail() {
IntNode cursor;
for (cursor = head; cursor != null; cursor = cursor.getLink()) {
return cursor;
public void insert(String name, int id){
head = new IntNode(name, id ,head);
count++;
public IntNode searchFor(String name) {
IntNode cursor;
cursor = head.listSearch(head, name);
return cursor;
public IntNode searchFor(int id) {
IntNode cursor;
cursor = head.listSearch(head, id);
return cursor;
public void print() {
IntNode cursor = head;
for (int i=0; i<count; i++) {
System.out.println(cursor.getName()+" "+cursor.getId());
cursor = cursor.getLink();
public void insertListBefore(IntNode match, StudentList list) {
IntNode preCursor = head.getPrevious(head, match);
IntNode cursor;
cursor = this.searchFor(match.getName());
preCursor.setLink(list.getHead());
list.getTail().setLink(cursor);
} -
Sup guys,
I have a question regarding how to use PrintJob class. Here is what I am trying to do, I am writing a simple gui app that takes the values from users and stores how many labels users want into a array.
So I get all the labels in the array and now I want to print them out of the array on the printer.
Two things, how dose someone go about setting up a PrinterJob so it reads the values from array and then sends it to the printer?
Also since I am printing labels this will be printed on a certain format. Now I use word to print these labels and they have a code in the word for it 5267, so I am not sure how I can get the program to print in that format so the labels come lined up correctly on the label sheet.
Is there another class in java that lets me import the word document and read the format and then somehow use that as a blueprint for what dimensions to use when printing?
Sorry, I am new to java so I am trying to figure out how these classes work and how to connect them together to get the program to do what I want.
Thanks for any helpLovac,
You should read more about Swing. There is a class called java.awt.print.PrintJob
for example
the method below will print the printable component; so your label should be layed on a printable component ( any component which implement Printable interface
such as you an have a class called MyJPanel which extends JPanel and implements the interface Printable;
example below show a printjob usage;
public void printData() {
try {
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(m_panel); // the m_panel extends JPanel and implements Printable interface
if (!prnJob.printDialog())
return;
setCursor( Cursor.getPredefinedCursor(
Cursor.WAIT_CURSOR));
prnJob.print();
setCursor( Cursor.getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
JOptionPane.showMessageDialog(this,
"Printing completed successfully",
APP_NAME, JOptionPane.INFORMATION_MESSAGE);
catch (PrinterException e) {
e.printStackTrace();
}Please take a look at java tutorial at http://java.sun.com/docs/books/tutorial/ui/features/index.html as a starting point
Regards,
Alan Mehio
London,UK
Maybe you are looking for
-
My iPhone Will Not Sync Since I Got My Laptop Back From Repair
I wanted to mention first that my laptop was repaired by a friend who is very well versed in all types of computer software and operating systems. I have Windows 7 and downloaded the most resent update of iTunes. I have been downloading different sof
-
Why does saving down from Illustrator 6 to older version sometimes not work?
We have some users with CS6 and some with CS3 and 4, when a user tries to open an illustrator file from CS3 and 4 saved down from CS6 it will not open. some files will open but most won't.
-
Do you recommend me "Learning Oracle 11g Training DVD - Tutorial Video"?
Hi I found on Amazon "Learning Oracle 11g Training DVD - Tutorial Video by InfiniteSkills". Is it worth it? There are no Amazon reviews :-( Do you use other video training? What do you recommend me?
-
Is it possible to delete e-mails from Nokia's mail...
Hello everyone, I have an E52 with the latest firmware, and I have a question about using it's built-in mail client. I'm using it with Yahoo mail. Is it possible to set up the mail client so that when I delete an e-mail message on my phone it doesn't
-
Table where Sap-Script Paragraph formats are stored
hey ABAP, does anyone know the table where the Paragraph formats are stored? Problem: we have a Form with 740 Paragraph formats, they all are of font-type courier, and now need to be either blank or Helve. and well i simply dont want to change 740 pa