gpt4 book ai didi

java - 获取每个JTextArea的文本

转载 作者:行者123 更新时间:2023-12-01 10:44:58 25 4
gpt4 key购买 nike

我有这样的代码:

public main() {
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700, 500);

//tabbed pane
add(tb);
}

public JTextArea txtArea() {
JTextArea area = new JTextArea();
String st = String.valueOf(tab);
area.setName(st);

return area;
}

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

@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();

if(source==mnew) {
tab++;

tb.add("Untitled-"+tab,new JPanel().add(txtArea()));

int s = tb.getSelectedIndex();
s = tb.getTabCount()-1;
tb.setSelectedIndex(s);
}

if(source==save) {
int s = tb.getSelectedIndex()+1;
}

每次单击“新建”菜单项,代码都会创建带有新面板和文本区域的新选项卡(它类似于许多文本编辑器,如 Notepad++ )。单击菜单栏中的“保存”后,我想从聚焦的 jtextarea 中获取文本。请帮忙。

最佳答案

向文本区域添加文档监听器。

public JTextArea txtArea() {
JTextArea area = new JTextArea();
tstDocumentListener dcL = new tstDocumentListener();
area.getDocument().addDocumentListener(dcL);
String st = String.valueOf(tab);
area.setName(st);

return area;
}

tstDocumentListener

public class tstDocumentListener implements DocumentListener
{
public void changedUpdate(DocumentEvent e) {}
public void removeUpdate(DocumentEvent e)
{
String newString = "";
int lengthMe = e.getDocument().getLength();
try
{
newString = e.getDocument().getText(0,lengthMe);

System.out.println(newString);
}

catch(Exception exp)
{
System.out.println("Error");
}
}
public void insertUpdate(DocumentEvent e)
{
String newString = "";
int lengthMe = e.getDocument().getLength();
try
{
newString = e.getDocument().getText(0,lengthMe);

System.out.println(newString);
}

catch(Exception exp)
{
System.out.println("Error");
}
}
}

编辑

当您获得或失去对文本区域的焦点时获取文本

public JTextArea txtArea() {
JTextArea area = new JTextArea();
CustomFocusListener cFL = new CustomFocusListener();
area.addFocusListener(cFL);
String st = String.valueOf(tab);
area.setName(st);

return area;
}

自定义焦点监听器

public class CustomFocusListener implements FocusListener
{
@Override
public void focusGained(FocusEvent e)
{
String parseMe = "";
JTextArea src;
try
{
src = (JTextArea)e.getSource();
parseMe = src.getText();
System.out.println(parseMe);
}
catch (ClassCastException ignored)
{

}
}

@Override
public void focusLost(FocusEvent e)
{
String parseMe = "";
JTextArea src;
try
{
src = (JTextArea)e.getSource();
parseMe = src.getText();
System.out.println(parseMe);
}
catch (ClassCastException ignored)
{

}
}
}

关于java - 获取每个JTextArea的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34239694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com