📄 printshapes.java
字号:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.print.*;
import javax.swing.*;
public class printShapes extends JPanel implements Printable, ActionListener{
final static JButton jbtn = new JButton("打印当前图形");
public printShapes() {
setBackground(Color.WHITE);
jbtn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintable(this);
if (pj.printDialog()) {
try {
pj.print();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
drawShapes(g2);
}
public void drawShapes(Graphics2D g2) {
int x = 30;
int y = 30;
g2.setColor(Color.BLUE);
g2.fill(new Arc2D.Double(x, y, x + 60, y + 120, 0, 270, Arc2D.PIE));
x += 55;
y += 85;
g2.setPaint(Color.RED);
g2.fill(new RoundRectangle2D.Double(x, y, 40, 40, 15, 15));
g2.setPaint(Color.black);
}
public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
if (pi >= 1) {
return Printable.NO_SUCH_PAGE;
}
drawShapes( (Graphics2D) g);
return Printable.PAGE_EXISTS;
}
public static void main(String s[]) {
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
JFrame jframe = new JFrame();
jframe.setTitle("打印图形");
jframe.addWindowListener(l);
JPanel jpanel = new JPanel();
jpanel.add(jbtn);
jframe.getContentPane().add(BorderLayout.SOUTH, jpanel);
jframe.getContentPane().add(BorderLayout.CENTER, new printShapes());
jframe.setSize(190, 250);
jframe.setVisible(true);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -