2024-03-18 18:51:49 | 我爱编程网
_db.asp
在这里找一下吧,我也帮你找找。
一个实现了JAVA打印接口的程序文件,用于打印文本框中的内容(通过打印机)
java下实现可打印文档实例源码
package weichang;
import java.awt.*;
import java.awt.print.*;
import java.awt.geom.*;
import java.awt.font.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.*;
/**
* This class implements the Pageable and Printable interfaces and allows
* the contents of any JTextComponent to be printed using the java.awt.print
* printing API.我爱编程网
**/
public class PrintableDocument implements Pageable, Printable {
View root; // The root View to be printed
PageFormat format; // Paper plus page orientation
double scalefactor; // How much to scale before printing
int numPages; // How many pages in the document
double printX, printY; // coordinates of upper-left of print area
double printWidth; // Width of the printable area
double printHeight; // Height of the printable area
Rectangle drawRect; // The rectangle in which the document is painted
// How lenient are we with the bottom margin in widow/orphan prevention?
static final double MARGIN_ADJUST = .97;
// The font we use for printing page numbers
static final Font headerFont = new Font("Serif", Font.PLAIN, 12);
/**
* This constructor allows printing the contents of any JTextComponent
* using a default PageFormat and a default scale factor. The default
* scale factor is .75 because the default fonts are overly large.
*/
public PrintableDocument(JTextComponent textComponent) {
this(textComponent, new PageFormat(), .75);
}
/**
* This constructor allows the contents of any JTextComponent to be
* printed, using any specified PageFormat object and any scaling factor.
**/
public PrintableDocument(JTextComponent textComponent, PageFormat format,
double scalefactor)
{
// Remember the page format, and ask it for the printable area
this.format = format;
this.scalefactor = scalefactor;
this.printX = format.getImageableX()/scalefactor;
this.printY = format.getImageableY()/scalefactor;
this.printWidth = format.getImageableWidth()/scalefactor;
this.printHeight = format.getImageableHeight()/scalefactor;
double paperWidth = format.getWidth()/scalefactor;
// Get the document and its root Element from the text component
Document document = textComponent.getDocument();
Element rootElement = document.getDefaultRootElement();
// Get the EditorKit and its ViewFactory from the text component
EditorKit editorKit =textComponent.getUI().getEditorKit(textComponent);
ViewFactory viewFactory = editorKit.getViewFactory();
// Use the ViewFactory to create a root View object for the document
// This is the object we'll print.
root = viewFactory.create(rootElement);
// The Swing text architecture requires us to call setParent() on
// our root View before we use it for anything. In order to do this,
// we need a View object that can serve as the parent. We use a
// custom implementation defined below.
root.setParent(new ParentView(root, viewFactory, textComponent));
// Tell the view how wide the page is; it has to format itself
// to fit within this width. The height doesn't really matter here
root.setSize((float)printWidth, (float)printHeight);
// Now that the view has formatted itself for the specified width,
// Ask it how tall it is.
double documentHeight = root.getPreferredSpan(View.Y_AXIS);
// Set up the rectangle that tells the view where to draw itself
// We'll use it in other methods of this class.
drawRect = new Rectangle(0, 0, (int)printWidth+1, (int)documentHeight+1);
// Now if the document is taller than one page, we have to
// figure out where the page breaks are.
if (documentHeight > printHeight) paginate(root, drawRect);
// Once we've broken it into pages, figure out how many pages.
numPages = pageLengths.size() + 1;
}
// This is the starting offset of the page we're currently working on
double pageStart = 0;
/**
* This method loops through the children of the specified view,
* recursing as necessary, and inserts pages breaks when needed.
* It makes a rudimentary attempt to avoid "widows" and "orphans".
**/
protected void paginate(View v, Rectangle2D allocation) {
// Figure out how tall this view is, and tell it to allocate
// that space among its children
double myheight = v.getPreferredSpan(View.Y_AXIS);
v.setSize((float)printWidth, (float)myheight);
// Now loop through each of the children
int numkids = v.getViewCount();
for(int i = 0; i < numkids; i++) {
View kid = v.getView(i); // this is the child we're working with
// Figure out its size and location
Shape kidshape = v.getChildAllocation(i, allocation);
if (kidshape == null) continue;
Rectangle2D kidbox = kidshape.getBounds2D();
// This is the Y coordinate of the bottom of the child
double kidpos = kidbox.getY() + kidbox.getHeight() - pageStart;
// If this is the first child of a group, then we want to ensure
// that it doesn't get left by itself at the bottom of a page.
// I.e. we want to prevent "widows"
if ((numkids > 1) &amt;&amt; (i == 0)) {
// If it is not near the end of the page, then just move
// on to the next child
if (kidpos < printY + printHeight*MARGIN_ADJUST) continue;
// Otherwise, the child is near the bottom of the page, so
// break the page before this child and place this child on
// the new page.
breakPage(kidbox.getY());
continue;
}
// If this is the last child of a group, we don't want it to
// appear by itself at the top of a new page, so allow it to
// squeeze past the bottom margin if necessary. This helps to
// prevent "orphans"
if ((numkids > 1) &amt;&amt; (i == numkids-1)) {
// If it fits normally, just move on to the next one
if (kidpos < printY + printHeight) continue;
// Otherwise, if it fits with extra space, then break the
// page at the end of the group
if (kidpos < printY + printHeight/MARGIN_ADJUST) {
breakPage(allocation.getY() + allocation.getHeight());
continue;
}
}
// If the child is not the first or last of a group, then we use
// the bottom margin strictly. If the child fits on the page,
// then move on to the next child.
if (kidpos < printY+printHeight) continue;
// If we get here, the child doesn't fit on this page. If it has
// no children, then break the page before this child and continue.
if (kid.getViewCount() == 0) {
breakPage(kidbox.getY());
continue;
}
// If we get here, then the child did not fit on the page, but it
// has kids of its own, so recurse to see if any of those kids
// will fit on the page.
paginate(kid, kidbox);
}
}
// For a document of n pages, this list stores the lengths of pages
// 0 through n-2. The last page is assumed to have a full length
ArrayList pageLengths = new ArrayList();
// For a document of n pages, this list stores the starting offset of
// pages 1 through n-1. The offset of page 0 is always 0
ArrayList pageOffsets = new ArrayList();
/**
* Break a page at the specified Y coordinate. Store the necessary
* information into the pageLengths and pageOffsets lists
**/
void breakPage(double y) {
double pageLength = y-pageStart-printY;
pageStart = y-printY;
pageLengths.add(new Double(pageLength));
pageOffsets.add(new Double(pageStart));
}
/** Return the number of pages. This is a Pageable method. */
public int getNumberOfPages() { return numPages; }
/**
* Return the PageFormat object for the specified page. This is a
* Pageable method. This implementation uses the computed length of the
* page in the returned PageFormat object. The PrinterJob will use this
* as a clipping region, which will prevent extraneous parts of the
* document from being drawn in the top and bottom margins.
**/
public PageFormat getPageFormat(int pagenum) {
// On the last page, just return the user-specified page format
if (pagenum == numPages-1) return format;
// Otherwise, look up the height of this page and return an
// appropriate PageFormat.
double pageLength = ((Double)pageLengths.get(pagenum)).doubleValue();
PageFormat f = (PageFormat) format.clone();
Paper p = f.getPaper();
if (f.getOrientation() == PageFormat.PORTRAIT)
p.setImageableArea(printX*scalefactor, printY*scalefactor,
printWidth*scalefactor, pageLength*scalefactor);
else
p.setImageableArea(printY*scalefactor, printX*scalefactor,
pageLength*scalefactor, printWidth*scalefactor);
f.setPaper(p);
return f;
}
/**
* This Pageable method returns the Printable object for the specified
* page. Since this class implements both Pageable and Printable, it just
* returns this.
**/
public Printable getPrintable(int pagenum) { return this; }
/**
* This is the basic Printable method that prints a specified page
**/
public int print(Graphics g, PageFormat format, int pageIndex) {
// Return an error code on attempts to print past the end of the doc
if (pageIndex >= numPages) return NO_SUCH_PAGE;
// Cast the Graphics object so we can use Java2D operations
Graphics2D g2 = (Graphics2D)g;
// Translate to accomodate the top and left margins
g2.translate(format.getImageableX(), format.getImageableY());
// Scale the page by the specified scaling factor
g2.scale(scalefactor, scalefactor);
// Display a page number centered in the area of the top margin.
// Set a new clipping region so we can draw into the top margin
// But remember the original clipping region so we can restore it
if (pageIndex > 0) {
Shape originalClip = g.getClip();
g2.setClip(new Rectangle(0, (int)-printY,
(int)printWidth, (int)printY));
// Compute the header to display, measure it, then display it
String numString = "- " + (pageIndex+1) + " -";
// Get string and font measurements
FontRenderContext frc = g2.getFontRenderContext();
Rectangle2D numBounds = headerFont.getStringBounds(numString, frc);
LineMetrics metrics = headerFont.getLineMetrics(numString, frc);
g2.setFont(headerFont); // Set the font
g2.setColor(Color.black); // Print with black ink
g2.drawString(numString, // Display the string
(int)((printWidth-numBounds.getWidth())/2),
(int)(-(printY-numBounds.getHeight())/2 +
metrics.getAscent()));
g2.setClip(originalClip); // Restore the clipping region
}
// Get the staring position and length of the page within the document
double pageStart = 0.0, pageLength = printHeight;
if (pageIndex > 0)
pageStart = ((Double)pageOffsets.get(pageIndex-1)).doubleValue();
if (pageIndex < numPages-1)
pageLength = ((Double)pageLengths.get(pageIndex)).doubleValue();
// Scroll so that the appropriate part of the document is lined up
// with the upper-left corner of the page
g2.translate(0.0, -pageStart);
// Now paint the entire document. Because of the clipping region,
// only the desired portion of the document will actually be drawn on
// this sheet of paper.
root.paint(g2, drawRect);
// Finally return a success code
return PAGE_EXISTS;
}
public void jobprint(){
PrinterJob job=PrinterJob.getPrinterJob();
job.setPrintable(this,job.defaultPage());
if(job.printDialog()){
try {
job.print();
}
catch (PrinterException ex) {
}
}
}
/**
* This inner class is a concrete implementation of View, with a
* couple of key method implementations. An instance of this class
* is used as the parent of the root View object we want to print
**/
static class ParentView extends View {
ViewFactory viewFactory; // The ViewFactory for the hierarchy of views
Container container; // The Container for the hierarchy of views
public ParentView(View v, ViewFactory viewFactory, Container container)
{
super(v.getElement());
this.viewFactory = viewFactory;
this.container = container;
}
// These methods return key pieces of information required by
// the View hierarchy.
public ViewFactory getViewFactory() { return viewFactory; }
public Container getContainer() { return container; }
// These methods are abstract in View, so we've got to provide
// dummy implementations of them here, even though they're never used.
public void paint(Graphics g, Shape allocation) {}
public float getPreferredSpan(int axis) { return 0.0f; }
public int viewToModel(float x,float y,Shape a,Position.Bias[] bias) {
return 0;
}
public Shape modelToView(int pos, Shape a, Position.Bias b)
throws BadLocationException {
return a;
}
}
}
如果
public static void main(String[] args) throws IOException
{
test_for_printer_4 test = new test_for_printer_4();
}
这个是你程序启动的入口,那么请问你,printFileAction这个方法怎么被调用呢 ?
用两个for循环,一个参数递增,另一个参数递减,代码如下:
public static void main(String[] args){
for (int i = 1; i <= 9; i++){
for(int n = 1; n <= i; n++) {
System.out.print( i + " x " + n + " = " + i * n + "\t");
}
System.out.println();
}
运行结果如下:
扩展资料:
Java中有三种主要的循环结构:
1、while 循环
while是最基本的循环,它的结构为:
while( 布尔表达式 ) {
//循环内容}
只要布尔表达式为 true,循环就会一直执行下去。
2、do…while 循环
对于 while 语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次。
do…while 循环和 while 循环相似,不同的是,do…while 循环至少会执行一次。
do {
//代码语句}while(布尔表达式);
3、for 循环
for循环执行的次数是在执行前就确定的。语法格式如下:
for(初始化; 布尔表达式; 更新) {
//代码语句}
参考资料:
Oracle官方API接口-Java™ Platform, Standard Edition 7API Specification
W3cSchool-Java 循环结构 - for, while 及 do…while
python怎么打印分数?python3.6代码:cnt=0whileTrue:print("请输入分数:")i=input()if(noti):print("输入有误!")print("学生人数:"+str(cnt))inti;min=max=score[0];avg=0;for(i=0;i<n;i++
怎么样把JAVA语言写的项目变成可以运行的程序有两种比较易用的方法:关于两种将Java程序转化为.exe程序工具的使用及比较一JSmooth1.出品Jsmooth,Sourceforge.net2.类型free3.下载4.步骤a)利用Eclipse将所需要的主类打成可独立运行的jar包,注意添加manifest属性和MainClass。b)新建一
编译java程序的命令是什么,运行java应用程序的命令是什么?当前默认目录为C盘Users文件夹下的Administrator文件夹。一般而言,我们习惯改变当前目录。由于windows有磁盘分区,若要跳到其他磁盘,例如E盘,有几种方法:1、输入命令:pushd路径(此命令可将当前目录设为所希望的任一个已存在的路径)2、输入命令:e: 转移到e盘,然后再输入cd转移
java获取运行时间很多朋友都想知道java怎么获取运行时间?下面就一起来了解一下吧~第一种是以毫秒为单位计算的。//伪代码long startTime=System.currentTimeMillis(); //获取开始时间doSomeThing(); //测试的代码段long endTime=System.currentTimeMillis(); //获取结束时间System.
python中n的阶乘的算法?1、首先定义一个ns数组用来存储n!的各个位数上的数值,利用for循环给ns加入10000个0值,以方便后面直接根据index对数组进行操作。然后定义length作为“数组的长度”(有真实数值的而非自动添加的0)也即n!的结果的位数。2、res=n。然后写入forrange循环,具体代码如下:foriinrange(1,n):接下来在for循环当中进行计
java程序的怎么运行,源程序已经写好并保存,如何使用命令提示符解释点击电脑左下角的开始,在点击运行,出入cmd··回车,命令提示符出现后,输入cd\回车··换行,然后输入javac(你的文件名).java回车··进行编译,编译成功后输入java(你的文件名)回车··运行程序!怎么在电脑上运行Java源程序代码首先你要在你的电脑上安装jdk。你可以在后面链
为什么CMD无法运行python程序用cmd运行python程序步骤:(1)打开cmd。(2)转到要运行的文件所在的盘(例如:E盘)。输入:e:回车(3)打开你要运行的文件所在的文件夹(例如:E:\ABC\123)。输入:cdE:\ABC\123回车(4)运行程序。输入:python***.py(程序文件的名字)回车为什么在IE中打不开Python?
java程序怎么实现的双击直接运行要想双击运行,需要将编译后的程序打包成Jar包,这样只要使用者电脑上装了JRE并且jar文件默认关联到JRE。这样jar文件就会显示为Java图标并且双击会自动运行。关于jar包深入了解可以搜一下jar包格式方面信息,主要是主类名称和类路径的设置。还有一种方式是把jar包再打包为EXE文件(仅限Windows下使用),无特殊理由不推荐。ja
2024-03-02 02:58:47
2024-01-01 09:58:48
2024-01-26 10:37:53
2024-03-04 07:43:42
2024-01-17 23:29:33
2024-01-01 04:24:22