2

JTabbedpane を使用するスイング アプリケーションを作成しています。タブでログ ファイルを開き、必要に応じて別のタブに「解析」できます。解析されたコンテンツをテキスト ファイルに保存する際に問題が発生しています。各タブは、JPanel 内の JTextarea で構成されます。

<pre>
 private void setContentsOfParsedLogFile(JPanel content) {
    JTextArea textArea = new JTextArea();
    addContentsToTextArea(textArea);
    content.add(new JScrollPane(textArea));
    content.setLayout(new GridLayout(1, 1));
    pane.addTab(parsedTabName(), content);
  }

  private void addContentsToTextArea(JTextArea textArea) {
    if (!parsedFileAlreadyOpen()) {
      PortLogParser lp = new PortLogParser();
      lp.parseLogFile(new File(activeTabFullName));
      ArrayList<String> sb = lp.getParsedMsg();
      for (String s : sb) {
        textArea.append(s + System.getProperty("line.separator"));
      }
    }
  }
</pre>

次を使用してテキストを取得できることを望んでいました。

String text = ((JTextArea) pane.getSelectedComponent()).getText();

アクション内で実行:

<pre>
  private void createSaveFileMenuItem() {
    saveLogFile = new JMenuItem("Save Log File");
    saveLogFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.ALT_MASK));
    saveLogFile.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        saveContentOfActiveTab();
      }
    });
  }

  private void saveContentOfActiveTab() {
    JFileChooser fc = new JFileChooser();
    int returnVal = fc.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File file = fc.getSelectedFile();
      try {
        saveContentsToFile(file);
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }

  private void saveContentsToFile(File file) throws IOException {
    createNewFileIfItDoesntExist(file);
    BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
    //System.out.println(pane.getSelectedIndex());
    //System.out.println(pane.getSelectedComponent());
    /*
    TODO
    the component is the container JPanel. How do I select the textarea and it's content??
    */
    //    String text = ((JTextArea) pane.getSelectedComponent()).getText();
    //    bw.write(text);
    bw.close();
  }

  private void createNewFileIfItDoesntExist(File file) throws IOException {
    if (!file.exists()) {
      file.createNewFile();
    }
  }
</pre>

ただし、選択したコンポーネントは JPanel です。JPanelに含まれるテキストエリア内のテキストを選択する方法はありますか? 各テキストエリアを一意に識別していないため、問題になる可能性がありますか?

4

1 に答える 1

3

JPanelこれを行う1つの方法は、以下を関連付けてのサブクラスを作成することですJTextArea

class LogTextPanel extends JPanel {

    private final JTextArea textArea;

    public LogTextPanel() {
        super(new GridLayout(1, 1));

        textArea = new JTextArea();
        add(new JScrollPane(textArea));
    }

    public void append(String text) {
        textArea.append(text);
    }

    public String getText() {
        return textArea.getText();
    }
}

次に、以下を使用して、選択したパネルからテキストを取得できます。

String text = ((LogTextPanel)pane.getSelectedComponent()).getText();
于 2012-12-26T16:22:54.460 に答える