📄 enhancedprintingexample.java
字号:
package JFCBook.Chapter4.jdk13;import java.awt.*;import java.awt.event.*;import java.io.*;import java.util.*;import javax.swing.*;public class EnhancedPrintingExample { // Handles the setup button public static void doSetup() { // Display the print dialog.... JobAttributes jobAttrs = getDefaultJobAttributes(); jobAttrs.setDialog(JobAttributes.DialogType.NATIVE); PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob( frame, "Printer Setup", jobAttrs, getDefaultPageAttributes()); if (pj != null) { pj.end(); } } // Prints without user intervention public static void doQuickPrint() { PrintJob pj = null; try { // Use the default settings for this - there will // be no printer dialog PageAttributes pageAttrs = new PageAttributes(getDefaultPageAttributes()); JobAttributes jobAttrs = new JobAttributes(getDefaultJobAttributes()); jobAttrs.setDialog(JobAttributes.DialogType.NONE); jobAttrs.setDefaultSelection(JobAttributes.DefaultSelectionType.ALL); pageAttrs.setOrigin(PageAttributes.OriginType.PRINTABLE); pj = Toolkit.getDefaultToolkit().getPrintJob(frame, "Java File Print", jobAttrs, pageAttrs); // Print using the default settings print(pj, pageAttrs, jobAttrs); } finally { if (pj != null) { pj.end(); } } } // Displays a print dialog and then prints public static void doPrint() { PrintJob pj = null; try { // Initialise the dialog from the default settings and // display a dialog for the user to make changes. PageAttributes pageAttrs = new PageAttributes(getDefaultPageAttributes()); JobAttributes jobAttrs = new JobAttributes(getDefaultJobAttributes()); jobAttrs.setDialog(JobAttributes.DialogType.NATIVE); pageAttrs.setOrigin(PageAttributes.OriginType.PRINTABLE); pj = Toolkit.getDefaultToolkit().getPrintJob(frame, "Java File Print", jobAttrs, pageAttrs); // Print using the user's settings print(pj, pageAttrs, jobAttrs); } finally { if (pj != null) { pj.end(); } } } // Gets the default page attributes, creating them // if necessary. private static PageAttributes getDefaultPageAttributes() { if (defaultPageAttributes == null) { setupDefaultAttributes(); } return defaultPageAttributes; } // Gets the default job attributes, creating them // if necessary. private static JobAttributes getDefaultJobAttributes() { if (defaultJobAttributes == null) { setupDefaultAttributes(); } return defaultJobAttributes; } // Sets up the initial default job and page attributes private static void setupDefaultAttributes() { defaultPageAttributes = new PageAttributes(); defaultJobAttributes = new JobAttributes(); // Get printer specifics, without displaying // a dialog. PrintJob pj = null; defaultJobAttributes.setDialog(JobAttributes.DialogType.NONE); pj = Toolkit.getDefaultToolkit().getPrintJob(frame, "", defaultJobAttributes, defaultPageAttributes); pj.end(); } private static void print(PrintJob pj, PageAttributes page, JobAttributes job) { Dimension d = statusLabel.getSize(); try { // Print the file content statusLabel.setText("Printing file..."); statusLabel.paintImmediately(0, 0, d.width, d.height); int printerResolution = pj.getPageResolution(); Dimension pageSize = pj.getPageDimension(); // Extract values from the PageAttributes and JobAttributes int lastPage = job.getToPage(); int[][] pages = job.getPageRanges(); boolean allPages = (job.getDefaultSelection() != JobAttributes.DefaultSelectionType.RANGE); BitSet bits = new BitSet(); if (!allPages) { // Set one bit for each page to be printed. for (int i = 0; i < pages.length; i++) { int lowPage = pages[i][0]; int highPage = pages[i][1]; for (int j = lowPage; j <= highPage; j++) { bits.set(j); } } } int copies = job.getCopies(); for (int i = 0; i < copies; i++) { String data; int pageNumber = 1; boolean printPage = allPages || bits.get(pageNumber); // Get a Graphics object for the printer. Graphics g = pj.getGraphics(); g.setFont(font); // Get font metrics from the printer graphics FontMetrics fm = g.getFontMetrics(); int fontHeight = fm.getHeight(); int fontAscent = fm.getAscent(); int line = fontAscent; // Pixel line on page int column = 0; // Pixel column on page // Leave room for page number at foot of page int maxLine = pageSize.height - 3 * fontHeight; int tabGap = 8 * fm.stringWidth(" "); boolean isTab; // True when we find a Tab BufferedReader r = new BufferedReader(new FileReader(file)); statusLabel.setText("Printing started"); statusLabel.paintImmediately(0, 0, d.width, d.height);printLoop: while((data = r.readLine()) != null) { if (data.equals("")) { data = " "; } StringTokenizer st = new StringTokenizer(data, " \t", true); while (st.hasMoreElements() == true) { String token = (String)st.nextElement(); isTab = token.equals("\t"); int stringWidth; if (isTab == true) { int nextCol = ((column + tabGap)/tabGap) * tabGap; stringWidth = nextCol - column; } else { stringWidth = fm.stringWidth(token); } if (column + stringWidth > pageSize.width) { line += fontHeight; column = 0; if (isTab == true) { stringWidth = tabGap; } if (line > maxLine) { // Page full - move to next page if (printPage) { // Print page number at the bottom statusLabel.setText("Printed page " + pageNumber); statusLabel.paintImmediately(0, 0, d.width, d.height); g.drawString("Page " + pageNumber, 32, maxLine + 2 * fontHeight); g.dispose(); // Flush page if (!allPages && pageNumber == lastPage) { // Printed last page g = null; break printLoop; } g = pj.getGraphics(); // Access to printer g.setFont(font); } pageNumber++; printPage = allPages || bits.get(pageNumber); line = fontAscent; column = 0; } } if (printPage && isTab == false) { g.drawString(token, column, line); } column += stringWidth; } // End of line: go to next line column = pageSize.width; } // End of file, or all required pages printed. r.close(); // Close file if (g != null) { g.drawString("Page " + pageNumber, 32, maxLine + 2 * fontHeight); g.dispose(); // Print the last page } } } catch (Exception e) { System.out.println("Exception while reading file data: " + e); } finally { statusLabel.setText("Printing completed"); statusLabel.paintImmediately(0, 0, d.width, d.height); } } public static void main(String[] args) { final JTextArea textArea = new JTextArea(20, 30); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); frame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); JPanel controls = new JPanel(new BorderLayout()); JPanel topPanel = new JPanel(new BorderLayout()); JLabel l = new JLabel("File Name: "); final JTextField fileField = new JTextField(); topPanel.add(l, BorderLayout.WEST); topPanel.add(fileField, BorderLayout.CENTER); JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton setupButton = new JButton("Setup..."); final JButton printButton = new JButton("Print..."); final JButton quickPrintButton = new JButton("Quick Print"); quickPrintButton.setEnabled(false); printButton.setEnabled(false); bottomPanel.add(setupButton); bottomPanel.add(printButton); bottomPanel.add(quickPrintButton); controls.add(topPanel, BorderLayout.NORTH); controls.add(bottomPanel, BorderLayout.CENTER); statusLabel = new JLabel(" "); controls.add(statusLabel, BorderLayout.SOUTH); frame.getContentPane().add(controls, BorderLayout.SOUTH); fileField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { String fileName = fileField.getText(); try { file = new File(fileName); textArea.read(new FileReader(file), null); } catch (IOException ex) { textArea.setText("Failed to open file " + fileName); file = null; } quickPrintButton.setEnabled(file != null); printButton.setEnabled(file != null); } }); setupButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { // Do printer setup. doSetup(); } }); printButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { // Prompt for settings and print doPrint(); } }); quickPrintButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { // Print without further user intervention doQuickPrint(); } }); frame.pack(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } }); frame.setVisible(true); } private static JFrame frame = new JFrame("Enhanced Printing Example"); private static File file; private static JLabel statusLabel; private static Font font = new Font("serif", Font.PLAIN, 12); // Default page attributes private static PageAttributes defaultPageAttributes; // Default job attributes private static JobAttributes defaultJobAttributes;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -