我对Java很陌生,我只是想通过阅读教科书来自学。教科书为applet提供以下代码:
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
我的一个练习就是让它点击后点击的按钮变得不可见。
在'actionPerformed'的'reponse.setVisible(true);'下面我尝试插入代码:
aButton.setVisible(false);
但是这给了我一个错误信息,我不确定还有什么可以改变现有的代码,使按钮在点击后消失。
答案 0 :(得分:2)
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方法中的按钮,它将向actionListener添加按钮,然后动作监听器将读取该按钮,如果按钮被认为是源(只是意味着单击按钮或对动作做出反应),它将触发setVisible(false)方法,创建按钮变为不可见,并希望为您提供所需的输出
我希望这有帮助! :)