import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WelcomeTest {
public static void main(String[] args) {
WelcomeFrame frame=new WelcomeFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class WelcomeFrame extends JFrame{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public WelcomeFrame(){
setTitle("Welcome");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
WelcomePanel panel=new WelcomePanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
}
class WelcomePanel extends JPanel{
public WelcomePanel(){
JLabel prompt=new JLabel("请输入您的名字:");
final JTextField input=new JTextField(10);
final JTextField output=new JTextField(25);
JButton btnn=new JButton("Welcome");
add(prompt);
add(input);
add(output);
add(btnn);
//btnn.addActionListener(this);
//public void actionPerformed(ActionEvent e){
//String s= input.getText();
//output.setText("Hello "+s+",欢迎参加考试!!");
//}
}
}
请问下被我注释起来的那一部份应该怎么写啊
------解决方案--------------------
/btnn.addActionListener(this);
//public void actionPerformed(ActionEvent e){
//String s= input.getText();
//output.setText("Hello "+s+",欢迎参加考试!!");
//}
你这里的this指的是按钮,所以拿不到input对象,可以这样写
写个监听类
public class MyListener implements ActionListener{
WelcomeFrame wf;
MyListener(WelcomeFrame wf){
this.wf=wf;
}
public void actionPerformed(ActionEvent e) {
String s=this.wf.input.getText();
this.wf.output.setText("Hello "+s+" ");
}
}
添加监听
MyListener myListener=new MyListener(this);
btnn.addActionListener(myListener);
------解决方案--------------------
public class WelcomeTest implements ActionListener{...}lz要学会看报什么错,然后对号入座。。