Domanda

I'm working on a small GUI application where I'm supposed to open a text document in a JTextPane. It's working fine except that when I add a DocumentListener to my JTextPane, the listener's not being called.

Here's the SSCE:

//GUI.java

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

class GUI

{

 public static void main(String[] args)

 {
  final JFrame frame = new JFrame("Frame");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  final JTabbedPane Tab = new JTabbedPane();

  JMenuBar MenuBar = new JMenuBar();

  JMenu File = new JMenu("File");
  File.setMnemonic('F');

  JMenuItem Open = new JMenuItem("Open");

  File.add(Open);
  MenuBar.add(File);

  Open.addActionListener(new ActionListener()
  {
   public void actionPerformed(ActionEvent eaal)
   {
    JFileChooser fc = new JFileChooser(".");
    int response = fc.showOpenDialog(frame);
    try{
     BufferedReader reader = new BufferedReader(new FileReader(fc.getSelectedFile())));
     JTextPane Text = new JTextPane();
     Text.getDocument().addDocumentListener(new DocumentChangeListener());
     Text.read(reader,null);
     Tab.add(fc.getSelectedFile().toString(), Text);
    }
    catch(Exception ea)
    {}
   }
  });

  frame.add(Tab);
  frame.setJMenuBar(MenuBar);
  frame.setSize(450,450);
  frame.setLocationRelativeTo(null);
  frame.setVisible(true);  
 }

}

//DocumentChangeListener.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class DocumentChangeListener implements DocumentListener
{
 public void changedUpdate(DocumentEvent edcl){}
 public void insertUpdate(DocumentEvent edcl)
 {
  System.out.println("Inserted");
 }
 public void removeUpdate(DocumentEvent edcl){}
}

What am I doing wrong here?

Thanks!

È stato utile?

Soluzione 2

read creates a new Document for the JTextComponent so addDocumentListener needs to be called after calling it rather than before

text.read(reader, null);
text.getDocument().addDocumentListener(new DocumentChangeListener());

Altri suggerimenti

The problem is that when you say Text.read, you're changing the document.

Move Text.getDocument().addDocumentListener(new DocumentChangeListener()); to after Text.read(reader,null); and you should be good!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top