请问这个代码我哪里错了,就是下面文字框里输入文字,上面显示出来
Java code
import java.awt.*;
import java.awt.event.*;
public class ChatClint {
public static void main(String[] args) {
new ChatClintFrame();
}
}
class ChatClintFrame extends Frame{
TextField sendText = new TextField(300);
TextArea showText = new TextArea("欢迎您!",40,1);
public ChatClintFrame() {
setBounds(400,160,380,500);
setTitle("ChatClint");
setLayout(new BorderLayout());
add(sendText,BorderLayout.SOUTH);
add(showText,BorderLayout.NORTH);
addWindowListener(new ChatClintClose()) ;
sendText.addActionListener(new SendMessage());
setVisible(true);
}
/*运行Launch文件
public void launchChatClintFrame() {
new ChatClintFrame();
}
*/
}
class ChatClintClose extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
class SendMessage implements ActionListener{
public void actionPerformed(ActionEvent e){
TextField sendText = (TextField)e.getSource();
String s = sendText.getText();
sendText.setText("");
TextArea showText;
showText.setText(s); //这里注掉以后可以运行不报错,但是没达到我的要求,为什么呢?
}
}
最后一行 注掉以后可以运行不报错,但是没达到我的要求,为什么呢?
------解决方案--------------------楼上的确实可以,平行类是无法直接引用ChatClint这个类里面的变量的,如果要用的话,就要想办法把变量从ChatClint传递到SendMessage,通过构造方法是最好的。
------解决方案--------------------import java.awt.*;
import java.awt.event.*;
public class ChatClint {
public static void main(String[] args) {
new ChatClintFrame();
}
}
class ChatClintFrame extends Frame{
TextField sendText = new TextField(300);
TextArea showText = new TextArea("欢迎您!",40,1);
public ChatClintFrame() {
setBounds(400,160,380,500);
setTitle("ChatClint");
setLayout(new BorderLayout());
add(sendText,BorderLayout.SOUTH);
add(showText,BorderLayout.NORTH);
addWindowListener(new ChatClintClose()) ;
sendText.addActionListener(new SendMessage(showText));
setVisible(true);
}
/*运行Launch文件
public void launchChatClintFrame() {
new ChatClintFrame();
}
*/
}
class ChatClintClose extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
class SendMessage implements ActionListener{
TextArea showText;
public SendMessage(TextArea showText){
this.showText = showText;
}
public void actionPerformed(ActionEvent e){
TextField sendText = (TextField)e.getSource();
String s = sendText.getText();
sendText.setText("");
showText.setText(s); //这里注掉以后可以运行不报错,但是没达到我的要求,为什么呢?
}
}
lz你试试这个吧。