我一直在努力创建一个程序,输入到JTextArea的数据会被计算,然后在点击按钮后在JLabel上显示单词数。
但是我尝试使用的代码,每次只显示1的值。
知道为什么吗? ` import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SPanel extends JPanel {
public SPanel(){
final TextAPanel textPanel = new TextAPanel();
final JLabel outputLabel = new JLabel();
JButton click = new JButton ("Click");
click.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
String word = textPanel.inputBox.getText();
System.out.println("Test: " +word);
}
});
}
}
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TextAPanel extends JPanel {
public JTextArea inputBox = new JTextArea(20,10);
public JScrollPane scrollPane = new JScrollPane(inputBox);
TextAreaPanel(){
JLabel title = new JLabel("Please type in the box below:");
inputBox.setLineWrap(true);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.NORTHWEST;
gc.gridx = 0;
gc.gridy = 0;
add(title,gc);
gc.gridx = 0;
gc.gridy = 1;
add(scrollPane, gc);
}
}
只是将它放在上下文中,我的JTextArea位于包含按钮和JLabel的面板的单独面板/类上。
每次运行程序并单击按钮,输入一些单词后,即使文本框为空,该值也始终为1。
答案 0 :(得分:0)
好吧,如果您创建一个新的TextAPanel
并将其分配给textPanel
变量 - 那么当您尝试获取输入时,您什么也得不到,因为新创建的面板不包含任何内容。如果textPanel
是您班级中的某个字段,则应该删除textPanel = new TextAPanel();
行,它应该可以正常工作。如果你得到一个NullPointerException,这意味着你忘了在代码中早先初始化它,你应该在构造函数中这样做。
TextAreaPanel()
方法/构造函数,这导致我的Eclipse中出现编译错误。无论如何,我有这个工作,你需要完成它,但这应该让你开始:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
@SuppressWarnings("serial")
public class SPanel extends JPanel {
public SPanel() {
final TextAPanel textPanel = new TextAPanel();
this.add(textPanel);
final JLabel outputLabel = new JLabel();
JButton click = new JButton("Click");
click.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String word = textPanel.inputBox.getText();
System.out.println("Test: " + word);
System.out.println(word.split("\\s+").length);
}
});
this.add(click);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.add(new SPanel());
f.setVisible(true);
}
}
@SuppressWarnings("serial")
class TextAPanel extends JPanel {
public JTextArea inputBox = new JTextArea(20, 10);
public JScrollPane scrollPane = new JScrollPane(inputBox);
TextAPanel() {
JLabel title = new JLabel("Please type in the box below:");
inputBox.setLineWrap(true);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.NORTHWEST;
gc.gridx = 0;
gc.gridy = 0;
add(title, gc);
gc.gridx = 0;
gc.gridy = 1;
add(scrollPane, gc);
}
}