JMenu Элемент для экспорта Jgraph как изображение
У меня есть jframe с jgraph init, и я добавил jmenu bar. Я пытаюсь этот код, чтобы добавить элемент jmenu, так что при нажатии он будет экспортировать jgraph как изображение в выбранном месте.
Я получаю следующие ошибки:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(Unknown Source)
at javax.imageio.ImageIO.getWriter(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)
at GUIquery$2.actionPerformed(GUIquery.java:440)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
И код:
final static mxGraph graph = new mxGraph() ;
final static mxGraphComponent graphComponent = new mxGraphComponent(graph);
public class GUI extends JFrame {
....
public static JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
//dimiurgia tu menubar
menuBar = new JMenuBar();
//1o menu
menu = new JMenu("Menu");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription("Info");
menuBar.add(menu);
// menu items
menuItem = new JMenuItem("Export as Image",KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription("Saves Diagram as Image (.PNG)");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
String filename ="Image";
exportImage(filename, graph, graphComponent);
}catch (IOException e) {
System.out.println("Image could not be read");
System.exit(1);
}
}
});
menu.add(menuItem);
menu.addSeparator();
//submenu
submenu = new JMenu("Preferences");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("Option A");
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Option B");
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menu.add(submenu);
// 2o menu
menu = new JMenu("View");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription( "View");
menuBar.add(menu);
menuItem = new JMenuItem("Info",KeyEvent.VK_A);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription("Info");
menu.add(menuItem);
menuItem = new JMenuItem("Flow",KeyEvent.VK_B);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription("Flow");
menu.add(menuItem);
menuBar.add(menu);
return menuBar;
}
protected static void exportImage(String filename, mxGraph graph, mxGraphComponent graphComponent) throws IOException{
BufferedImage image = mxCellRenderer.createBufferedImage(graph, null, 1, Color.WHITE, graphComponent.isAntiAlias(), null,graphComponent.getCanvas());
// Creates the URL-encoded XML data
mxCodec codec = new mxCodec();
String xml = URLEncoder.encode(mxXmlUtils.getXml(codec.encode(graph.getModel())), "UTF-8");
mxPngEncodeParam param = mxPngEncodeParam.getDefaultEncodeParam(image);
param.setCompressedText(new String[] { "graph", xml });
// Saves as a PNG file
FileOutputStream outputStream = new FileOutputStream(new File(filename));
try
{
mxPngImageEncoder encoder = new mxPngImageEncoder(outputStream,param);
if (image != null)
{
encoder.encode(image);
}
else
{
System.out.println("No Image");
}
}
finally
{
outputStream.close();
}
}
1 ответ
Возможно, это не лучший ответ, который вы ожидаете, но похоже, что нужно заплатить за jgraph, чтобы получить его. Пока не ответит какая-нибудь библиотека jgraph, возможно, это даст вам подсказку.
Исключение говорит "java.lang.IllegalArgumentException: image == null!" и я бы обвинял один из нулевых параметров или неисправность здесь:
BufferedImage image = mxCellRenderer.createBufferedImage(graph, null, 1, Color.WHITE,
graphComponent.isAntiAlias(), null,graphComponent.getCanvas());
Вы можете проверить, поставив нулевую проверку следующим образом:
mxPngEncodeParam param = null;
if(image != null) {
param = mxPngEncodeParam.getDefaultEncodeParam(image);
} else {
System.out.println("No Image in pngparam creation");
System.exit(1);
}
или просто положить некоторые точки останова в режиме отладки.
НТН