当前位置: 代码迷 >> Java相关 >> 不能运行啊
  详细解决方案

不能运行啊

热度:258   发布时间:2006-03-29 16:59:00.0
不能运行啊
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
public class Work3 extends JFrame implements ActionListener{
protected JButton btn;
protected JLabel lbl;
public Work3(){
setTitle("beautifule avril");
setSize(200,200);
//ImageIcon icon1 =new ImageIcon("D:/myjava/tupian.nba.gif");
// ImageIcon icon2 =new ImageIcon("D:/myjava/tupian.avril1.gif");
JLabel lbl =new JLabel("oh oh",JLabel.BOTTOM);
JButton btn =new JButton("avril");
//btn.setVerticalTextPosition(AbstractButton.BOTTOM);
Container cp;
cp=getContentPane();
cp.add(lbl);
cp.add(btn);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
lbl.setText("hi my name is avril");
}
public static void main(String[] args){
Work3 work =new Work3();
work.show();

}
} 这个程序怎么编译通过了但不能运行
搜索更多相关的解决方案: 运行  

----------------解决方案--------------------------------------------------------
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
public class Work3 extends JFrame implements ActionListener{
protected JButton btn;
protected JLabel lbl;
public Work3(){
setTitle("beautifule avril");
setSize(200,200);
//ImageIcon icon1 =new ImageIcon("D:/myjava/tupian.nba.gif");
// ImageIcon icon2 =new ImageIcon("D:/myjava/tupian.avril1.gif");
lbl =new JLabel("oh oh");
JButton btn =new JButton("avril");
//btn.setVerticalTextPosition(AbstractButton.BOTTOM);
Container cp;
cp=getContentPane();
cp.add(lbl,BorderLayout.NORTH);
cp.add(btn,BorderLayout.SOUTH);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
lbl.setText("hi my name is avril");
}
public static void main(String[] args){
Work3 work =new Work3();
work.setVisible(true);

}
}


首先你这个程序,lbl先是设置成了全局变量,可是你在你的构造函数里面又定义了一次, 你这么做的后果是在调用事件函数的时候,你所持有的lbl的引用是空的,当然这个时候会产生异常
还有,你用了被列为过时的方法show,,我帮你改回为setVisible()了
还有,你构造JLabel的时候弄错了,JLabel是没有你写的那个的构造函数的
还有,你把对象加入容器中的时候,没有指定它的位置 ,这使得后加入的按钮把前加入的JLabel盖掉了
还有,不推荐你这样使用事件函数的方法,里面什么都没有判 断,直接设置lbl的值,这样不好
----------------解决方案--------------------------------------------------------
真是太感谢了 一定会努力得
----------------解决方案--------------------------------------------------------
  相关解决方案