简体   繁体   English

使用JFileChooser打开文件并在JFrame / JPanel中显示

[英]Open file with JFileChooser and display it in JFrame/JPanel

So Im trying to create swing gui in NetBeans IDE. 因此,我试图在NetBeans IDE中创建Swing GUI。 Im new to java and building gui's so its been a little bit of a learning curve. 我是Java和构建gui的新手,所以它有点像学习曲线。

I created a JMenuItem called "Open" and used JFileChooser to open a file and display it. 我创建了一个名为“ Open”的JMenuItem,并使用JFileChooser打开了一个文件并显示它。 The file extension im limiting myself to is "*.map". 我限制自己使用的文件扩展名是“ * .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. 但即时通讯试图弄清楚如何在JFrame而不是新窗口中打开文件。 Its not a .txt file so i assume i cant use JTextArea or JTextField. 它不是.txt文件,所以我认为我不能使用JTextArea或JTextField。 Do i create a JPanel inside of my JFrame? 我是否可以在JFrame中创建一个JPanel?

Here's a my ActionPerformed event code: 这是我的ActionPerformed事件代码:

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. 最终弄清楚了如何在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); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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