Reputation: 83
So I have a JTextPane
, and I have a method that returns a String
containing the text in the JTextPane
. I have been trying to fix this for weeks. The getText()
method returns a blank line. I tried getting the document length, but that returns 0.
Here is the code:
import java.awt.*;
import javax.swing.*;
public class CodeTabs extends JTabbedPane {
private JTextPane codearea;
private JScrollPane scroll;
public CodeTabs() {
setTabPlacement(JTabbedPane.BOTTOM);
codearea = new JTextPane();
scroll = new JScrollPane(codearea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize()));
addTab("Code", scroll);
}
public String getCode() {
String s = codearea.getText();
System.out.println(s);
return s;
}
}
Upvotes: 0
Views: 3982
Reputation: 36601
I took your code and added a main method and a button to trigger the getCode()
method. Everything works as expected. When I type something in the text area, it gets printed when I press the button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CodeTabs extends JTabbedPane {
private JTextPane codearea;
private JScrollPane scroll;
public CodeTabs() {
setTabPlacement(JTabbedPane.BOTTOM);
codearea = new JTextPane();
scroll = new JScrollPane(codearea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setPreferredSize(new Dimension( 300,300 ));
JPanel panel = new JPanel( new BorderLayout() );
panel.add( scroll, BorderLayout.CENTER );
JButton comp = new JButton( "Print text" );
comp.addActionListener( new ActionListener() {
@Override
public void actionPerformed( ActionEvent e ) {
getCode();
}
} );
panel.add( comp, BorderLayout.SOUTH );
addTab( "Code", panel );
}
public String getCode() {
String s = codearea.getText();
System.out.println(s);
return s;
}
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame( "TestFrame" );
frame.getContentPane().add( new CodeTabs() );
frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
} );
}
}
Note: there is no need to extend JTabbedPane
. Use it instead of extending it (I left it in the code posted in this answer to match your code as closely as possible)
Upvotes: 2
Reputation: 18064
Do this way:-
codearea.getDocument().getText(0, codearea.getDocument().getLength());
Upvotes: 0