Java 从选项卡窗格检索textarea

Java 从选项卡窗格检索textarea,java,swing,file-io,jtextarea,Java,Swing,File Io,Jtextarea,我试图保存选项卡式窗格中面板上的文本区域的内容 到目前为止,我已经尝试: bw.write(tabbedPane.getComponent(tabbedPane.getSelectedIndex()).toString()); 我一直在研究tabbedpane的所有方法,但我似乎无法解决它。我知道我必须从选项卡窗格中获取所选组件,然后从中获取文本区域,然后将其转换为我假设的字符串 打开文件时的代码是: private void btnOpenActionPerformed(java.awt.e

我试图保存选项卡式窗格中面板上的文本区域的内容

到目前为止,我已经尝试:

bw.write(tabbedPane.getComponent(tabbedPane.getSelectedIndex()).toString());
我一直在研究tabbedpane的所有方法,但我似乎无法解决它。我知道我必须从
选项卡窗格
中获取所选组件,然后从中获取文本区域,然后将其转换为我假设的字符串

打开文件时的代码是:

private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {

    int returnVal = fileChooser.showOpenDialog(this);

    if (returnVal == fileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        try {
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());

            JTextArea x = new JTextArea();
            JScrollPane scroll = new JScrollPane(x);
            p.add(scroll, BorderLayout.CENTER);            

            x.read( new FileReader( file.getAbsolutePath() ), null );
            File selectedFile = fileChooser.getSelectedFile();
            String name = selectedFile.getName();
            tabbedPane.add(p,name);
            tabbedPane.setSelectedComponent(p);
        } catch (IOException ex) {
            System.out.println("problem accessing file"+file.getAbsolutePath());
        }
    } else {
        System.out.println("File access cancelled by user.");
    }
}
我已经按照你的坚持增加了课程 更新当前的另存为方法:

private void btnSaveAsActionPerformed(java.awt.event.ActionEvent evt) {

    int returnVal = fileChooser.showSaveDialog(this);

    if (returnVal == fileChooser.APPROVE_OPTION) {
        File dir1 = fileChooser.getCurrentDirectory();
        String dir = dir1.getPath();
        String name = fileChooser.getSelectedFile().getName() + ".txt";

        try {
            File file = new File(dir,name);
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            JPanel no = (JPanel) tabbedPane.getSelectedComponent();
            JTextArea bo = (JTextArea) no.get
            bw.write(bo.getText());
            bw.close();
            tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), name);
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
当前打开的文件方法:

private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {

    int returnVal = fileChooser.showOpenDialog(this);

    if (returnVal == fileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();

        try {
            FilePanel p = new FilePanel(file);
            tabbedPane.add(p,p.getName());
            tabbedPane.setSelectedComponent(p);
        } catch (IOException ex) {
            System.out.println("problem accessing file"+file.getAbsolutePath());
        }
    } else {
        System.out.println("File access cancelled by user.");
    }
}

我是否需要将新类的新对象添加到数组中,还是只将它们插入到选项卡窗格中就可以了?

这里没有什么神奇之处,而是您如何编写代码。持有JTextArea的类应该有一个公共方法,类似于返回JTextArea的
getTextArea()
。然后,当您通过
getSelectedComponent()
获取所选选项卡的组件时,可以对返回的组件调用此方法


编辑
根据您发布的代码,您需要重新思考您的程序设计。您的JTextArea是一个局部变量,因此不容易访问,这就是您的问题所在。我建议:

  • 首先也是最重要的一点,停止使用Swing代码生成器软件,至少在您了解Java和Swing的基础知识之前不要这样做,因为这会妨碍您获得这种理解
  • 通过Java和Swing教程学习如何手工编写Swing代码
  • 如果需要访问特定组件,请确保它们是类字段,并且可以通过getter方法访问它们,或者更好的是,只能访问感兴趣组件的特定属性。例如,如果希望文本保存在JTextArea中,而不是使用返回JTextArea的
    getTextArea()
    方法,则使用仅返回JTextArea保存的文本的
    getTextAreaText()
    。代码对外部干扰和副作用的限制越大越好。
编辑2
例如,您可以创建一个在JPanel中保存JTextArea的类,类似于:

class FilePanel extends JPanel {

   private File file;
   private JTextArea textArea;
   private String name;

   public FilePanel(File file) throws FileNotFoundException, IOException {
      this.file = file;
      setLayout(new BorderLayout());

      textArea = new JTextArea();
      JScrollPane scroll = new JScrollPane(textArea);
      add(scroll, BorderLayout.CENTER);

      textArea.read(new FileReader(file.getAbsolutePath()), null);
      name = file.getName();
   }

   public File getFile() {
      return file;
   }

   public JTextArea getTextArea() {
      return textArea;
   }

   public String getName() {
      return name;
   }

}
然后,无论何时从JTextPane获取selectedComponent,确保它不为null,将其强制转换为FilePanel并对其调用getTextArea()


编辑3
例如:

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;

public class FooSwing extends JFrame {
   private static final int PREF_W = 600;
   private static final int PREF_H = 450;
   private JFileChooser fileChooser = new JFileChooser();
   private JTabbedPane tabbedPane = new JTabbedPane();

   public FooSwing() {
      JPanel btnPanel = new JPanel();
      btnPanel.add(new JButton(new AbstractAction("Open") {

         @Override
         public void actionPerformed(ActionEvent e) {
            btnOpenActionPerformed(e);
         }
      }));
      btnPanel.add(new JButton(new AbstractAction("Get Selected Text") {

         @Override
         public void actionPerformed(ActionEvent e) {
            FilePanel selectedComp = (FilePanel)tabbedPane.getSelectedComponent();
            if (selectedComp != null) {
               String text = selectedComp.getTextArea().getText();
               System.out.println(text);
            } else {
               System.out.println("No component selected");
            }
         }
      }));

      add(tabbedPane, BorderLayout.CENTER);
      add(btnPanel, BorderLayout.SOUTH);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {

      int returnVal = fileChooser.showOpenDialog(this);

      if (returnVal == JFileChooser.APPROVE_OPTION) {
         File file = fileChooser.getSelectedFile();

         try {
            JPanel filePanel = new FilePanel(file);

            tabbedPane.add(filePanel, filePanel.getName());
            tabbedPane.setSelectedComponent(filePanel);
         } catch (IOException ex) {
            System.out.println("problem accessing file"
                  + file.getAbsolutePath());
         }
      } else {
         System.out.println("File access cancelled by user.");
      }
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShow();
         }
      });
   }

   private static void createAndShow() {
      FooSwing fooSwing = new FooSwing();
      fooSwing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      fooSwing.pack();
      fooSwing.setLocationRelativeTo(null);
      fooSwing.setVisible(true);
   }
}

class FilePanel extends JPanel {

   private File file;
   private JTextArea textArea;
   private String name;

   public FilePanel(File file) throws FileNotFoundException, IOException {
      this.file = file;
      setLayout(new BorderLayout());

      textArea = new JTextArea();
      JScrollPane scroll = new JScrollPane(textArea);
      add(scroll, BorderLayout.CENTER);

      textArea.read(new FileReader(file.getAbsolutePath()), null);
      name = file.getName();
   }

   public File getFile() {
      return file;
   }

   public JTextArea getTextArea() {
      return textArea;
   }

   public String getName() {
      return name;
   }

}

就像我在你的报告中提到的。发布SSCCE、复制/粘贴错误和异常输出。如果您包含更多的实际代码,可能会有所帮助。也许是在您创建文本区域和选项卡等的地方。@leigero“如果您包含更多的实际代码可能会有所帮助”问题通常是OP不知道哪些代码相关,哪些不相关。SSCCE解决了这个问题。@tbodt:为什么要删除您的答案?你在我投票之前就删除了它。我做了所有的事情,但我仍然无法访问方法getTextArea,除非我这样做:FilePanel no=(FilePanel)tabbedPane.getSelectedComponent();JTextArea bo=(JTextArea)编号getTextArea();它抛出了一个错误:java.lang.ClassCastException:javax.swing.JPanel不能转换为texteditor。FilePanel@Steve:不要复制我的代码。复制我的想法,编写你自己的代码,它很可能会工作。@Steve:也要相信错误信息告诉你的。如果它给你一个错误,说你试图将一个通用的JPanel转换为其他东西,那么你实际上是在这样做——试图将一个JPanel转换为其他东西,解决办法是不要这样做。我理解,但我试图做的是访问当前选中的选项卡,并调用getTextArea方法,但我不知道该怎么做。我这样做是为了大学里的一个项目:)@Steve:我已经解释过了。您必须用自定义类对象填充JTabbedPane,然后我向您展示了一个示例。你还没做这件事,所以我不知道如何进一步帮助你。