1

我对Java很陌生,我只是想通过一本教科书自学。教科书提供了一个小程序的如下代码:

import java.awt.Container;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SavitchCh6Prjct14 extends JApplet implements ActionListener
{

private JLabel response;
private Container contentPane;
public void init()
{
    contentPane = getContentPane();
    contentPane.setBackground(Color.WHITE);

    //Create Button:
    JButton aButton = new JButton("Push me!");
    aButton.addActionListener(this);
    //create label
    response = new JLabel("Thanks. That felt good!");
    ImageIcon smileyFaceIcon = new ImageIcon("smiley.jpg"); 
    response.setIcon(smileyFaceIcon);
    response.setVisible(false);//invisible until button is clicked.
    //Add button:
    contentPane.setLayout(new FlowLayout());
    contentPane.add(aButton);
    //Add Label
    contentPane.add(response);
}//end init
public void actionPerformed(ActionEvent e)
{
    contentPane.setBackground(Color.PINK);
    response.setVisible(true);//show label when true

}//end actionPerformed
}//end class

我的一个练习是让点击的按钮在被点击后变得不可见。

在“reponse.setVisible(true);”下的“actionPerformed”中 我尝试插入代码: aButton.setVisible(false);

但这给了我一条错误消息,我不确定还能做些什么来改变这个现有的代码以使按钮在被点击后消失。

4

1 回答 1

2

在 performAction 方法中,您必须找到正在设置的对象,因此您只需编写以下代码来代替您的方法:

 public void actionPerformed(ActionEvent e)
 {
     contentPane.setBackground(Color.PINK);
     response.setVisible(true);//show label when true

     if(e.getSource() == aButton) {
         aButton.setVisible(false);
     }

 }//end actionPerformed

但是将按钮创建为全局按钮,因此由您的

 private JLabel response;
 private Container contentPane;

添加按钮

 private JLabel response;
 private Container contentPane;
 public JButton aButton;

然后在init方法中,就做

 aButton = new JButton("Push me!");

并保持

 aButton.addActionListener(this);

这会将按钮创建为全局变量,让整个程序都可以查看它,它将在 init 方法中初始化按钮,它将动作侦听器添加到按钮上,然后动作侦听器将读取按钮,如果按钮被认为是源(仅表示按钮被单击或对动作做出反应)它将触发 setVisible(false) 方法,使按钮变得不可见,并希望为您提供所需的输出

我希望这有帮助!:)

于 2013-06-09T21:06:42.847 回答