1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.hipparchus.samples;
23
24 import java.awt.Component;
25 import java.awt.Graphics2D;
26 import java.awt.event.ActionEvent;
27 import java.awt.event.ActionListener;
28 import java.awt.event.InputEvent;
29 import java.awt.event.KeyEvent;
30 import java.awt.image.BufferedImage;
31 import java.io.File;
32 import java.io.IOException;
33
34 import javax.imageio.ImageIO;
35 import javax.swing.JFileChooser;
36 import javax.swing.JFrame;
37 import javax.swing.JMenu;
38 import javax.swing.JMenuBar;
39 import javax.swing.JMenuItem;
40 import javax.swing.KeyStroke;
41 import javax.swing.SwingUtilities;
42
43
44
45 public class ExampleUtils {
46
47
48
49
50
51
52
53
54 public ExampleUtils() {
55
56 }
57
58
59 @SuppressWarnings("serial")
60 public static class ExampleFrame extends JFrame {
61
62
63
64
65
66
67
68
69 public ExampleFrame() {
70
71 }
72
73
74
75
76
77
78
79
80
81 public Component getMainPanel() {
82 return getContentPane();
83 }
84 }
85
86
87
88
89 public static void showExampleFrame(final ExampleFrame frame) {
90 Runnable r = new Runnable() {
91 public void run() {
92 JMenuItem screenshot = new JMenuItem("Screenshot (png)");
93 screenshot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0, InputEvent.CTRL_DOWN_MASK));
94 screenshot.addActionListener(new ActionListener() {
95 public void actionPerformed(ActionEvent ae) {
96 JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
97 if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
98 File file = fileChooser.getSelectedFile();
99 BufferedImage img = getScreenShot(frame.getMainPanel());
100 try {
101
102 ImageIO.write(img, "png", file);
103 } catch (IOException e) {
104 e.printStackTrace();
105 }
106 }
107 }
108 });
109
110 JMenuItem exit = new JMenuItem("Exit");
111 exit.addActionListener(new ActionListener() {
112 public void actionPerformed(ActionEvent e) {
113 System.exit(0);
114 }
115 });
116
117 JMenu menu = new JMenu("File");
118 menu.add(screenshot);
119 menu.add(exit);
120 JMenuBar mb = new JMenuBar();
121 mb.add(menu);
122 frame.setJMenuBar(mb);
123
124 frame.setLocationRelativeTo(null);
125 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
126 frame.setVisible(true);
127 }
128 };
129 SwingUtilities.invokeLater(r);
130 }
131
132 private static BufferedImage getScreenShot(Component component) {
133 BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB);
134
135 component.paint(image.getGraphics());
136 return image;
137 }
138
139
140
141
142
143
144
145
146 public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height, int type) {
147 BufferedImage resizedImage = new BufferedImage(width, height, type);
148 Graphics2D g = resizedImage.createGraphics();
149 g.drawImage(originalImage, 0, 0, width, height, null);
150 g.dispose();
151 return resizedImage;
152 }
153
154 }