📄 hiresprintexample.java
字号:
package JFCBook.Chapter4.jdk13;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*;import java.net.*;import java.util.*;public class HiResPrintExample { // Create default page and job attributes static void print(Image image) { PageAttributes page = new PageAttributes(); JobAttributes job = new JobAttributes(); // Set up to use the printable area and install // the desired resolution. page.setColor(PageAttributes.ColorType.COLOR); page.setOrigin(PageAttributes.OriginType.PRINTABLE); int dpi = 72; try { dpi = Integer.parseInt(resolution.getText()); } catch (NumberFormatException e) { System.out.println("Illegal resolution - using 72dpi"); } System.out.println("Printing at " + dpi + " dpi."); page.setPrinterResolution(dpi); PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob( frame, "Print Image", job, page); if (pj == null) { // Cancelled by user return; } // Print the image centered on the paper Dimension pageSize = new Dimension(pj.getPageDimension()); int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); // Use try/finally to release PrintJob even if we get an exception try { Graphics g = pj.getGraphics(); g.drawImage(image, (pageSize.width - imageWidth)/2, (pageSize.height - imageHeight)/2, null); g.dispose(); // Print the last page } catch (Exception e) { System.out.println("Exception while printing image: " + e); } finally { // Always terminate the print job pj.end(); System.out.println("Printing completed"); } } public static void main(String[] args) { // Load the image URL imageURL = HiResPrintExample.class.getResource("images/earth.jpg"); ImageIcon imageIcon = new ImageIcon(imageURL); final Image image = imageIcon.getImage(); JLabel label = new JLabel(imageIcon); frame.getContentPane().add(label, BorderLayout.CENTER); JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel.add(new JLabel("Resolution: ")); panel.add(resolution); panel.add(button); frame.getContentPane().add(panel, BorderLayout.SOUTH); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { print(image); } }); frame.pack(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } }); frame.setVisible(true); } static JFrame frame = new JFrame("Hi-res Printing Example"); static JTextField resolution = new JTextField("72", 10); static JButton button = new JButton("Print...");}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -