簡體   English   中英

如何在Java中單擊時使按鈕不可見?

[英]How to make a button invisible when clicked in java?

我正在研究教科書上的一個項目,但遇到了麻煩。 目標是:首次出現GUI時,兩個按鈕都可見,但是單擊一個按鈕時,該按鈕消失,只有另一個按鈕可見。 此后,只有一個按鈕可見。 單擊該按鈕時,它消失並且出現另一個按鈕

public class ButtonDemo extends JFrame implements ActionListener
{
    public static final int WIDTH = 400;
    public static final int HEIGHT = 300;

    public ButtonDemo()
    {
        setSize(WIDTH, HEIGHT);
        WindowDestroyer listener = new WindowDestroyer();
        addWindowListener(listener);

        Container contentPane = getContentPane();
        contentPane.setBackground(Color.WHITE);

        contentPane.setLayout(new FlowLayout());

        JButton sunnyButton = new JButton("Sunny");
        sunnyButton.addActionListener(this);
        contentPane.add(sunnyButton);
        JButton cloudyButton = new JButton("Cloudy");
        cloudyButton.addActionListener(this);
        contentPane.add(cloudyButton);
    }

    public void actionPerformed(ActionEvent e)
    {
        String actionCommand = e.getActionCommand();
        Container contentPane = getContentPane();

        if(actionCommand.equals("Sunny"))
        {
            contentPane.setBackground(Color.BLUE);
        }

        else if (actionCommand.equals("Cloudy"))
        {
            contentPane.setBackground(Color.GRAY);


        }
        else
            System.out.println("Error in button interface.");
    }
}

在按鈕上使用setVisible應該可以。 請嘗試以下操作:

將以下行移動到ButtonDemo的字段中:

JButton sunnyButton = new JButton("Sunny");
JButton cloudyButton = new JButton("Cloudy");

actionPerformed的if語句更改為:

if(actionCommand.equals("Sunny"))
{
    contentPane.setBackground(Color.BLUE);
    sunnyButton.setVisible(false);
    cloudyButton.setVisible(true);
}
else if (actionCommand.equals("Cloudy"))
{
    contentPane.setBackground(Color.GRAY);
    sunnyButton.setVisible(true);
    cloudyButton.setVisible(false);
}

這是非常簡單的代碼。 使sunnyButtoncloudyButton成為實例成員。

只需檢查動作事件的源並隱藏源組件並顯示另一個即可。

public void actionPerformed(ActionEvent e) {

    if (sunnyButton == e.getSource()) {
        sunnyButton.setVisible(false);
        cloudyButton.setVisible(true);
    } else if (cloudyButton == e.getSource()) {
        sunnyButton.setVisible(true);
        cloudyButton.setVisible(false);
    }
    ...
}

關於什么

source.setVisible(false) 

隱藏和

source.setVisible(true) 

顯示按鈕?

編輯:您應該獲取事件的來源(e.getSource())並將其隱藏

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM