Skip to content
Advertisement

I am not able to load a graph via JFileChooser and actually display it

So, I have a class that inherits from JFrame with two JSplitPanes and a menu bar. One JSplitPane has a JSplitPane on top and a textarea on the bottom and the other one two JPanels left and right. I want to parse a pnml-file (or more, but I’m just trying to get one working right now) that I chose via JFileChooser. I can choose a file and I tested it by printing the filename and that is working but I can’t manage to actually display the graph in the left JPanel. Maybe someone can help me with that. This is my class:

import pnml_parsing.Parser;
   
   import java.awt.BorderLayout;
   import java.awt.event.MouseAdapter;
   import java.awt.event.MouseEvent;
   import java.awt.event.ActionListener;
   import java.awt.event.ActionEvent;
   import java.io.File;
   import java.util.Arrays;
   
   import javax.swing.JComponent;
   import javax.swing.JFrame;
   import javax.swing.JLabel;
   import javax.swing.JPanel;
   import javax.swing.JScrollPane;
   import javax.swing.JSplitPane;
   import javax.swing.JTextArea;
   import javax.swing.JMenuBar;
   import javax.swing.JToolBar;
   import javax.swing.JMenu;
   import javax.swing.JMenuItem;
   import javax.swing.JButton;
   import javax.swing.JFileChooser;
   import javax.swing.filechooser.FileFilter;
   
   
   
   import org.graphstream.ui.swingViewer.ViewPanel;
   import org.graphstream.ui.view.Viewer;
   import org.graphstream.ui.view.ViewerPipe;
   
   
   
   public class Fenster_test extends JFrame {
       /** default serial version ID */
       private static final long serialVersionUID = 1L;
   
       
       private Controller controller;
   
       
       private ViewPanel viewPanel1;
       private ViewPanel viewPanel2;
   
       
       
       private JLabel statusLabel;
   
       
       JTextArea textfield = new JTextArea();
       JSplitPane leftRight = new JSplitPane();
       JComponent bottom = new JScrollPane(textfield);
       JPanel jpnlGraph = new JPanel(new BorderLayout());
       JPanel resultGraph = new JPanel(new BorderLayout());
       JLabel label = new JLabel();
       JToolBar tbar = new JToolBar();
       JMenuBar mbar = new JMenuBar();
       JMenu datei = new JMenu("Datei");
       JButton reset = new JButton("reset");
       JButton markerplus = new JButton("+");
       JButton markerminus = new JButton("-");
       JButton loescheEG = new JButton("EG löschen"); 
       JMenuItem dateiwahl = new JMenuItem("Datei auswählen");
       JMenuItem dateienwahl = new JMenuItem("Dateien auswählen");
       JFileChooser jfc = new JFileChooser();
       File[] files;
   
      
       
       
       final JSplitPane topBottom = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
   
       public Fenster_test(String titel) {
           super(titel);
           
           jfc.setMultiSelectionEnabled(true);
           jfc.setFileFilter(new FileFilter() {
   
                  public String getDescription() {
                      return "PNML Dateien (*.pnml)";
                  }
   
                  public boolean accept(File f) {
                      if (f.isDirectory()) {
                          return true;
                      } else {
                          String filename = f.getName().toLowerCase();
                          return filename.endsWith(".pnml") || filename.endsWith(".pnml") ;
                      }
                  }
               });
               
   
   
       
       
           System.setProperty("org.graphstream.ui.renderer",
                   "org.graphstream.ui.j2dviewer.J2DGraphRenderer");
   
           // Erzeuge Controllers
           //controller = new Controller(this);
   
           // Layout des JFrames setzen
           this.setLayout(new BorderLayout());
   
           // Erzeuge und initialisiere ein Panel zur Anzeige des Graphen
           //initPanelGraph();
   
           // Einbetten des ViewPanels ins JPanel
           //jpnlGraph = new JPanel(new BorderLayout());
           //jpnlGraph.add(BorderLayout.CENTER, viewPanel1);
           
           // Füge das JPanel zum Haupt-Frame hinzu
           this.add(jpnlGraph, BorderLayout.CENTER);
           mbar.add(datei);
           tbar.add(loescheEG);
           tbar.add(markerplus);
           tbar.add(markerminus);
           tbar.add(reset);
           datei.add(dateiwahl);
           //initPanelGraph();
           controller = new Controller(jpnlGraph);
           label.setText("<No Graph>");
           jpnlGraph.add(label);
           dateiwahl.addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                   
   
                   jfc.showOpenDialog(null);
                   files = jfc.getSelectedFiles();
                   
                   
                   if(files == null) {
                       System.out.println("Keine Datei(en) ausgewählt");
                   }else {
                   
                       Parser parser = new Parser(files[0]);
                       parser.initParser(); 
                       parser.parse(); //parses File
                       
                       initPanelGraph(); 
                       
                       
                   }
                   if(files.length>1) {
                       Arrays.sort(files);
                       //mehrere Dateien durchlaufen
                       for(int i=0; i<files.length; i++) {
                           System.out.println("Datei "+files[i].getPath()+"ausgewählt");
                       }
                       
                   }
                   jfc.setCurrentDirectory(files[0].getParentFile());
               }
           });
           
           
   
           mbar.add(tbar);
           this.setJMenuBar(mbar);
           this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           this.setBounds(200, 200, 400, 300);
   
             
   
           topBottom.setTopComponent(leftRight);
           topBottom.setBottomComponent(bottom);
   
           leftRight.setLeftComponent(jpnlGraph);
           leftRight.setRightComponent(resultGraph);
   
           this.add(topBottom, BorderLayout.CENTER);
           this.setSize(1000, 700);
           this.setVisible(true);
   
           topBottom.setDividerLocation(0.8);
           leftRight.setDividerLocation(0.5);
   
       }
   
       private void initPanelGraph() {
           Viewer viewer = new Viewer(controller.getGraph(),  //this method actually converts my own model of my pnml-File to Nodes and Edges for graphstream
                   Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
           viewer.disableAutoLayout();
   
           viewPanel1 = viewer.addDefaultView(false);
   
           ViewerPipe viewerPipe = viewer.newViewerPipe();
   
           ClickListener clickListener = new ClickListener(controller);
   
           viewerPipe.addViewerListener(clickListener);
   
           viewPanel1.addMouseListener(new MouseAdapter() {
   
               @Override
               public void mousePressed(MouseEvent me) {
                   System.out.println("MyFrame - mousePressed: " + me);
                   viewerPipe.pump();
               }
   
               @Override
               public void mouseReleased(MouseEvent me) {
                   System.out.println("MyFrame - mouseReleased: " + me);
                   viewerPipe.pump();
               }
           });
       }

Before I tried it with the JFileChooser and hardcoded the .pnml-path it worked fine. The constructor looked like this. Now I’m just calling new Fenster_test(“Name of my Frame”); in my main-Method and before I was also doing the parsing in the main-method.

    public Fenster_test(String titel) {
        super(titel);
    
        System.setProperty("org.graphstream.ui.renderer",
                "org.graphstream.ui.j2dviewer.J2DGraphRenderer");


        controller = new Controller(this);

        this.setLayout(new BorderLayout());

        
        initPanelGraph();


        jpnlGraph.add(BorderLayout.CENTER, viewPanel1);
        

        this.add(jpnlGraph, BorderLayout.CENTER);

        
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(200, 200, 400, 300);

          

        topBottom.setTopComponent(leftRight);
        topBottom.setBottomComponent(bottom);

        leftRight.setLeftComponent(jpnlGraph);
        leftRight.setRightComponent(resultGraph);

        this.add(topBottom, BorderLayout.CENTER);
        this.setSize(1024, 720);
       this.setVisible(true);

        topBottom.setDividerLocation(0.8);
        leftRight.setDividerLocation(0.5);
    
    }

    

Advertisement

Answer

Since you didn’t provide a minimal, runnable example, I created my own.

Here’s a simple image display GUI.

Image Display GUI

I created a JFrame with a drawing JPanel. The code to create the JFrame is in the run method. The drawing JPanel is created in a separate class. I extend JPanel because I want to override the paintComponent method.

Use this code to create a simple GUI that displays one of your medical images. Once you get that to work, carefully add code to your simple GUI. Test your GUI after each little bit (< 20 lines) of code that you add.

It’s not a good idea to use null layouts and absolute positioning. Swing was designed to be used with layout managers.

Here’s the complete runnable code.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;

public class ImageDisplay implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ImageDisplay());
    }
    
    private ImageDisplayModel model;
    
    private ImagePanel imagePanel;
    
    private JFrame frame;
    
    public ImageDisplay() {
        this.model = new ImageDisplayModel();
    }
    
    @Override
    public void run() {
        frame = new JFrame("Image Display");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setJMenuBar(createMenuBar());
        
        imagePanel = new ImagePanel(model);
        frame.add(imagePanel, BorderLayout.CENTER);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    
    private JMenuBar createMenuBar() {
        JMenuBar menubar = new JMenuBar();
        
        JMenu filemenu = new JMenu("File"); 
  
        JMenuItem openitem = new JMenuItem("Open...");
        openitem.addActionListener(new OpenFileListener(this, model));
        filemenu.add(openitem);
        
        menubar.add(filemenu);
        
        return menubar;
    }
    
    public void updateImagePanel(int width, int height) {
        imagePanel.setPreferredSize(width, height);
        imagePanel.repaint();
        frame.pack();
    }
    
    public JFrame getFrame() {
        return frame;
    }
    
    public class ImagePanel extends JPanel {

        private static final long serialVersionUID = 1L;
        
        private ImageDisplayModel model;
        
        public ImagePanel(ImageDisplayModel model) {
            this.model = model;
            this.setPreferredSize(649, 480);
        }
        
        public void setPreferredSize(int width, int height) {
            this.setPreferredSize(new Dimension(width, height));
        }
        
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            
            BufferedImage image = model.getImage();
            if (image != null) {
                g.drawImage(image, 0, 0, this);
            }
        }
        
    }
    
    public class OpenFileListener implements ActionListener {
        
        private ImageDisplay frame;
        
        private ImageDisplayModel model;

        public OpenFileListener(ImageDisplay frame, ImageDisplayModel model) {
            this.frame = frame;
            this.model = model;
        }

        @Override
        public void actionPerformed(ActionEvent event) {
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter(
                    "JPG & PNG Images", "jpg", "png");
            chooser.addChoosableFileFilter(filter);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            
            File file = model.getFile();
            if (file != null) {
                chooser.setCurrentDirectory(file);            
            }
            
            int result = chooser.showOpenDialog(frame.getFrame());
            if (result == JFileChooser.APPROVE_OPTION) {
                File selectedFile = chooser.getSelectedFile();
                model.setFile(selectedFile);
                BufferedImage image;
                try {
                    image = ImageIO.read(selectedFile);
                    model.setImage(image);
                    frame.updateImagePanel(image.getWidth(), 
                            image.getHeight());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }
    
    public class ImageDisplayModel {
        
        private BufferedImage image;
        
        private File file;

        public BufferedImage getImage() {
            return image;
        }

        public void setImage(BufferedImage image) {
            this.image = image;
        }

        public File getFile() {
            return file;
        }

        public void setFile(File file) {
            this.file = file;
        }
        
    }

}
Advertisement