我很困惑,但这对你来说似乎很简单。 [JAVA]
我已经实现了通过按下按钮执行的操作,假设它是 b1。按 b1 将浏览文件并将其输出到文本区域。我实现了另一个按钮,例如 b2,用于生成 token
这就是我想做的:
我希望 b2 对文本区域(text.getText())中的文本进行标记,其中文本区域的内容是由 b1 带来的。
问题是我无法对 b2 中 b1 产生的文本内容进行标记。它只给出空白结果。我怀疑它无法从 b1 获取文本,因为该文本不是全局的,并且仅位于 e.getSource==b1 条件内。
[编辑] 好的,在这里:
if(e.getSource()==button){
fileChooser= new JFileChooser();
returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
// What to do with the file, e.g. display it in a TextArea
text.read( new FileReader( file.getAbsolutePath() ), null );
}catch(IOException ex){}
}else{}
}
if(e.getSource()==b2){
String[] token= text.getText().split(" ");
System.out.println(token[0]);
}
当我将分词器放入 b1 条件时,它就可以工作。但上面没有。
似乎当我执行“text.getText()”时,它没有获得在 b1 中选择文件并将其输出到文本中所做的更改。这就是为什么我问是否有办法将 b1 完成的操作合并到 b2 中。
最佳答案
当我运行它时它起作用了。但不起作用的是尝试打印 token [0]
。当我打印整个内容时,它就起作用了。可能发生的情况是您不允许仅通过 .split("");
合并分隔符。如果文件开头有空格,这可能会导致第一个标记为零。我将其更改为 .split("[\\n\\s]+");
,它允许使用一个或多个字符的分隔符。
if (e.getSource() == b2) {
String[] token = text.getText().split("[\\n\\s]+");
for (String s : token) {
System.out.println(s);
}
}
或者也许您只是忘记将监听器注册到 b2
。 ?
这是运行示例
import java.awt.BorderLayout;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class Test3 extends JFrame {
JButton button;
JButton b2;
JTextArea text;
JFileChooser fileChooser;
int returnVal;
public Test3() {
text = new JTextArea(20, 40);
button = new JButton("Read");
button.addActionListener(new Listener());
b2 = new JButton("Write");
b2.addActionListener(new Listener());
add(button, BorderLayout.NORTH);
add(text, BorderLayout.CENTER);
add(b2, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test3();
}
});
}
private class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
fileChooser = new JFileChooser();
returnVal = fileChooser.showOpenDialog(Test3.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
// What to do with the file, e.g. display it in a TextArea
text.read(new FileReader(file.getAbsolutePath()), null);
} catch (IOException ex) {
}
} else {
}
}
if (e.getSource() == b2) {
String[] token = text.getText().split("[\\n\\s]+");
for (String s : token) {
System.out.println(s);
}
}
}
}
}
<小时/>
作为旁注。永远不要吞掉异常
} catch (IOException ex) {
}
在可以看到异常的地方放置一些有意义的内容,例如
} catch (IOException ex) {
ex.printStackTrace();
}
关于java - 将一个 Action 的结果合并到另一个 Action 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21140940/