请java大虾帮忙,程序老是不能写对!!

来源:百度知道 编辑:UC知道 时间:2024/05/29 23:46:47
你可以帮助我解决一个问题吗?
我写了一段代码,为了实现以下功能:
点击一个按钮,在按钮上循环显示:"显示"和"隐藏",其中为"显示"的按钮对应JLabel中的文字,而"隐藏"对应着JLabel中为空.
我写的代码不能实现以上功能,不知道是什么地方出错了,请大家指点一二!!
谢谢!!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* @author Administrator
*/
public class Xu2 implements ActionListener
{
JLabel lbl;
JButton btn;
/** Creates a new instance of Xu2 */
public Xu2()
{
JFrame f = new JFrame("xu2");
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(2,1));
lbl = new JLabel();
btn = new JButton("显示");
btn.addActionListener(this);
contentPane.add(lbl);
contentPane.add(btn);
f.setSize(300,200);
f.show();
f.addWindowListener(new WindowAdapter()
{
pub

e.getSource() 改成 e.getActionCommand()

e.getSource() 是用来比较对象的,不是用比较名字的

支持一楼作如下改动即可

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* @author Administrator
*/
public class Xu2 implements ActionListener
{
JLabel lbl;
JButton btn;
/** Creates a new instance of Xu2 */
public Xu2()
{
JFrame f = new JFrame("xu2");
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(2,1));
lbl = new JLabel();
btn = new JButton("显示");
btn.addActionListener(this);
contentPane.add(lbl);
contentPane.add(btn);
f.setSize(300,200);
f.show();
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});//Inner class
}
public static void main(String[] args)
{
new Xu2();