Search code examples
variablesjbuttonreturn-value

Make button turn visible when variable reaches certain value


I would like to know how you can make it so that a button turns visible as soons as a variable hits a certain value. it should be like an upgrade in a minigame, so that youre only able to click it when you have enough gold.

This is the button:

upgrade1 = new JButton("-50");
    upgrade1.setIcon(new javax.swing.ImageIcon(getClass().getResource("Pickaxe.png")));
    upgrade1.setBorderPainted(false);
    upgrade1.setFocusPainted(false);
    upgrade1.setContentAreaFilled(false);
    upgrade1.setBounds(200, 200, 150, 150);

this is its action listener:

upgrade1.addActionListener(new ActionListener() 
{

     public void actionPerformed(ActionEvent ae)
     {
         klicks -= 50;
         test.setText("Gold:" + " " + klicks);
         k = 2;
     }

});

This is the "Currency":

public int klicks=0;

Its put to zero because the player starts with 0 gold


Solution

  • On instanciation of the upgrade1 button, make it invisible upgrade1.setVisible(false);.

    Put the following code where you add gold to the user:

    if (klicks >= 50) {
        upgrade1.setVisible(true);
    }
    

    Make sure to set the button invisible if the gold drops below 50, for example if the user buys another item. Set it to invisible after the user has bought the upgrade as well.

    https://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#setVisible(boolean)