java—我无法通过jfilechooser加载图形并实际显示它

xkftehaa  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(357)

所以,我有一个继承自jframe的类,它有两个jsplitpane和一个菜单栏。一个jsplitpane在顶部有一个jsplitpane,在底部有一个textarea,另一个jsplitpane左右各有两个jpanel。我想解析一个通过jfilechooser选择的pnml文件(或者更多,但我现在只是想让一个工作)。我可以选择一个文件,并通过打印文件名对其进行测试,这是可行的,但我无法在左侧jpanel中实际显示图形。也许有人能帮我。这是我的课:

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();
               }
           });
       }

在我尝试使用jfilechooser和硬编码.pnml路径之前,它工作得很好。构造器看起来像这样。现在我只需要调用new fensterètest(“我的帧的名称”);在我的main方法中,之前我也在main方法中进行解析。

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);

    }
vhmi4jdf

vhmi4jdf1#

因为你没有提供一个最小的,可运行的例子,我创建了我自己的。
下面是一个简单的图像显示gui。

我创造了一个 JFrame 带着一幅画 JPanel . 创建 JFrame 是在 run 方法。图纸 JPanel 在单独的类中创建。我延伸 JPanel 因为我想覆盖 paintComponent 方法。
使用此代码可以创建一个简单的gui来显示一个医学图像。一旦你开始工作,小心地将代码添加到你的简单gui中。在添加的每一小段代码(<20行)之后测试gui。
使用空布局和绝对定位不是一个好主意。swing设计用于布局管理器。
下面是完整的可运行代码。

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;
        }

    }

}

相关问题