【发布时间】:2013-04-29 17:19:33
【问题描述】:
我看到很多人问过这样的问题,但它没有回答我的问题。我在 Java 方面还很新。我正在尝试从JTextField 获取一些输入并将其作为String 返回,以便我可以使用它在不同的类中进行比较。这就是我认为的答案,我希望能够在课堂的任何其他部分使用str。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class ClassFrame extends JFrame {
private static final long serialVersionUID = 2451829341034438685L;
public static JButton inputButton = new JButton("Send");
public static JTextArea editTextArea = new JTextArea("Type Here!");
public static JTextArea uneditTextArea = new JTextArea();
public ClassFrame(String title) {
//SET LAYOUT MANAGER (How it arranges components)
setLayout(new BorderLayout());
//////CREATE SWING COMPONENTS////////////
//OUTPUT TEXT AREA
uneditTextArea.setEditable(false);
//INPUT TEXT AREA
editTextArea.setBackground(Color.BLUE);
editTextArea.setForeground(Color.WHITE);
//SET CONTENT PANE
Container c = getContentPane();
//ADD COMPONENTS TO CONTENT PANE
c.add(uneditTextArea, BorderLayout.CENTER);
c.add(editTextArea, BorderLayout.SOUTH);
c.add(inputButton, BorderLayout.WEST);
ClassFrame.inputButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String str = editTextArea.getText();
editTextArea.setText(" ");
System.out.println(str);
}
});
}
}
【问题讨论】:
-
不要使用静态变量!!!
-
一个简单的
actionListener和field.getSource()会为你创造奇迹。
标签: java swing jtextfield