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
46 public class ExampleUtils {
47
48
49
50
51
52
53
54
55 public ExampleUtils() {
56
57 }
58
59
60 @SuppressWarnings("serial")
61 public static class ExampleFrame extends JFrame {
62
63
64
65
66
67
68
69
70 public ExampleFrame() {
71
72 }
73
74
75
76
77
78
79
80
81
82 public Component getMainPanel() {
83 return getContentPane();
84 }
85 }
86
87
88
89
90 public static void showExampleFrame(final ExampleFrame frame) {
91 Runnable r = new Runnable() {
92 public void run() {
93 JMenuItem screenshot = new JMenuItem("Screenshot (png)");
94 screenshot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0, InputEvent.CTRL_DOWN_MASK));
95 screenshot.addActionListener(new ActionListener() {
96 public void actionPerformed(ActionEvent ae) {
97 JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
98 if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
99 File file = fileChooser.getSelectedFile();
100 BufferedImage img = getScreenShot(frame.getMainPanel());
101 try {
102
103 ImageIO.write(img, "png", file);
104 } catch (IOException e) {
105 e.printStackTrace();
106 }
107 }
108 }
109 });
110
111 JMenuItem exit = new JMenuItem("Exit");
112 exit.addActionListener(new ActionListener() {
113 public void actionPerformed(ActionEvent e) {
114 System.exit(0);
115 }
116 });
117
118 JMenu menu = new JMenu("File");
119 menu.add(screenshot);
120 menu.add(exit);
121 JMenuBar mb = new JMenuBar();
122 mb.add(menu);
123 frame.setJMenuBar(mb);
124
125 frame.setLocationRelativeTo(null);
126 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
127 frame.setVisible(true);
128 }
129 };
130 SwingUtilities.invokeLater(r);
131 }
132
133 private static BufferedImage getScreenShot(Component component) {
134 BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB);
135
136 component.paint(image.getGraphics());
137 return image;
138 }
139
140
141
142
143
144
145
146
147 public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height, int type) {
148 BufferedImage resizedImage = new BufferedImage(width, height, type);
149 Graphics2D g = resizedImage.createGraphics();
150 g.drawImage(originalImage, 0, 0, width, height, null);
151 g.dispose();
152 return resizedImage;
153 }
154
155 }