[英]Cannot get text from JTextPane
So I have a JTextPane
, and I have a method that returns a String
containing the text in the JTextPane
. 所以我有一个
JTextPane
,我有一个方法返回一个包含JTextPane
本的String
。 I have been trying to fix this for weeks. 我一直在努力解决这个问题。 The
getText()
method returns a blank line. getText()
方法返回一个空行。 I tried getting the document length, but that returns 0. 我尝试获取文档长度,但返回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;
}
}
I took your code and added a main method and a button to trigger the getCode()
method. 我拿了你的代码并添加了一个main方法和一个按钮来触发
getCode()
方法。 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
. 注意:不需要扩展
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) 使用它而不是扩展它(我把它放在这个答案中发布的代码中,以尽可能地匹配你的代码)
这样做: -
codearea.getDocument().getText(0, codearea.getDocument().getLength());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.