当我按下按钮时,我试图将 JTextField 的输入拆分为单词数组。当我按下按钮时,程序会给我一个巨大的错误列表。分割句子的代码行以及我在操作监听器中调用该类的位置是 eclipse 所说错误的来源。我不知道为什么会收到此错误,也不知道如何修复。我尝试了很多不同的方法,但它们都不起作用。如果您能解释为什么这不起作用或如何解决,那就太好了。这是我的代码。感谢您的帮助。
主类:
public class Control {
public static void main(String[] args) {
OpenWindow ow = new OpenWindow();
ow.window();
}
}
二等:
public class OpenWindow extends JFrame{
//Making variables
String input;
String firstWord2;
JButton jb = new JButton("Button");
JLabel jl = new JLabel();
JTextField jtf = new JTextField(40);
JPanel jp1 = new JPanel(new GridLayout(3,1));
SentenceSplitter ss = new SentenceSplitter();
public void window() {
//Make window pop up
setTitle("Project");
setSize(600, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Action Listener
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input = jtf.getText();
//Error from line below
ss.split();
firstWord2 = ss.getFirstWord();
jl.setText(firstWord2);
}
});
//Add JFrames
jp1.add(jtf);
jp1.add(jb);
jp1.add(jl);
add(jp1);
}
//Make input accesible from other classes
String getInput() {
return input;
}
}
三等:
public class SentenceSplitter {
String firstWord;
public void split() {
OpenWindow ow2 = new OpenWindow();
//Get input
String sentence = ow2.getInput();
//Error from line below
String[] splitSentence = sentence.split(" ");
firstWord = splitSentence[0];
}
String getFirstWord() {
return firstWord;
}
}
最佳答案
在你的代码中
创建 OpenWindow
在 OpenWindow 对象中,您将创建一个
SentenceSplitter
并监听点击单击时,您将在之前创建的
SentenceSplitter
上调用split
方法在 split 中,您将创建一个新的
OpenWindow
您可能应该做的是将字符串作为输入参数传递给 split
方法
关于java - 按下 JButton 时分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25300328/