我看到類似這樣的問題,但它沒有回答我的問題。我在Java方面很新。我試圖從JTextField
獲得一些輸入,並將其作爲String
返回,以便我可以在不同的課程中使用它進行比較。這是我看到的答案,我希望能夠在班級的任何其他部分使用str
。Java swing從JTextField獲取輸入
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);
}
});
}
}
不要使用靜態變量! – camickr 2013-05-06 00:37:09
一個簡單的'actionListener'和'field.getSource()'會爲你創造奇蹟。 – Tdorno 2013-05-06 00:48:09