简体   繁体   中英

Open file with JFileChooser and display it in JFrame/JPanel

So Im trying to create swing gui in NetBeans IDE. Im new to java and building gui's so its been a little bit of a learning curve.

I created a JMenuItem called "Open" and used JFileChooser to open a file and display it. The file extension im limiting myself to is "*.map".

So i got my code working and it opens the chosen file in a new window on my desktop. But im trying to figure out how i can open the file inside of my JFrame and not a new window. Its not a .txt file so i assume i cant use JTextArea or JTextField. Do i create a JPanel inside of my JFrame?

Here's a my ActionPerformed event code:

private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
    try{
        JFileChooser chooser= new JFileChooser();
        chooser.setCurrentDirectory(new File("c:\\temp"));
        chooser.setFileFilter(new FileNameExtensionFilter("map","MAP"));
        int value = chooser.showOpenDialog(null);
        if(value == JFileChooser.APPROVE_OPTION){
            File selectedFile = chooser.getSelectedFile();
            String path = selectedFile.getAbsolutePath();

            File myFile = new File(path);
            Desktop.getDesktop().open(myFile);
            messageLabel.setText("Map successfully Loaded!");
        }
    }catch(Exception e){
        JOptionPane.showMessageDialog(null,e);
    }

Ended up figuring out how to display the file in a JTextArea. Thanks for the responses guys. Here is my updated code and its working just as i wanted.

  private void OpenActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser chooser= new JFileChooser(); chooser.setCurrentDirectory(new File("c:\\\\temp")); chooser.setFileFilter(new FileNameExtensionFilter("map","MAP")); int value = chooser.showOpenDialog(null); File f= chooser.getSelectedFile(); String filename= f.getAbsolutePath(); try{ FileReader reader = new FileReader(filename); BufferedReader br = new BufferedReader(reader); jTextArea1.read(br,null); br.close(); jTextArea1.requestFocus(); }catch(Exception e){ JOptionPane.showMessageDialog(null,e); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM