[英]How to set button to invisible in content pane/container
我對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
我的一項練習是使它變得如此,使單擊的按鈕在單擊后變得不可見。
在“ reactionse.setVisible(true);”下的“ actionPerformed”中 我嘗試插入代碼: aButton.setVisible(false);
但這給了我一個錯誤消息,我不確定是否可以通過其他方式更改此現有代碼,以使按鈕在單擊后消失。
在PerformanceAction方法中,您必須找到要設置的對象,因此只需將其寫成您的方法即可:
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)方法,使該按鈕變為不可見,並希望為您提供所需的輸出
我希望這有幫助! :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.