user2923839
user2923839

Reputation: 11

How to create a function to remove a button [Beginner]

I am currently using this function to create and display a button.

Button(String nm, int x, int y, int w, int h)
 {
  super(nm, x, y, w, h);
 }
 void display()
{
if(currentImage != null)
 {

  float imgWidth = (extents.y*currentImage.width)/currentImage.height;


  pushStyle();
  imageMode(CORNER);
  tint(imageTint);
  image(currentImage, pos.x, pos.y, imgWidth, extents.y);
  stroke(bgColor);
  noFill();
  rect(pos.x, pos.y, imgWidth,  extents.y);
  noTint();
  popStyle();
 }
else
 {
  pushStyle();
  stroke(lineColor);
  fill(bgColor);
  rect(pos.x, pos.y, extents.x, extents.y);

  fill(lineColor);
  textAlign(CENTER, CENTER);
  text(name, pos.x + 0.5*extents.x, pos.y + 0.5* extents.y);
  popStyle();
  }
}

I would like to create a function such as: void hide() so that I could remove or hide the function when I need to, after it is clicked. How should I approach this? am I basically setting everything to null? to remove it?

Upvotes: 0

Views: 99

Answers (2)

v.k.
v.k.

Reputation: 2854

Maybe a simple boolean show wrapping the display statements... And a key or what ever to toogle it.

like:

void display(){
  if(show){
  //all stuff
  }
}

void toogleShow(){
if(/*something, a key an event...*/){
show = !show;
  }
}

You would need to wrap functionality of the button as well.

Upvotes: 1

Michael Langowski
Michael Langowski

Reputation: 348

I can´t be sure now as you haven´t posted the actual class definition but I´m assuing you either extend java.awt.Button or javax.swing.JButton.

In that case, you can just use the setVisible method:

public void hide(){
    this.setVisible(false);
}

This works on every GUI-Component that extends java.awt.Component.

In a very simple example (that is a one-way thing since you can´t get the button back ;)) this would look like:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class DemoFrame extends JFrame {

    private JButton buttonToHide;

    public DemoFrame() {
        this.setSize(640, 480);
        buttonToHide = new JButton();
        buttonToHide.setText("Hide me!");
        buttonToHide.addActionListener(new ButtonClickListener());
        this.getContentPane().add(buttonToHide);
    }

    public class ButtonClickListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (buttonToHide.isVisible()) {
                buttonToHide.setVisible(false);
            }
        }
    }

    public static void main(String[] args){
        new DemoFrame().setVisible(true);
    }
}

While writing up that example I found that java.awt.Component even defines a method "hide()" but this is marked as deprecated with the hint to use setVisible instead.

I hope this helps!

Upvotes: 2

Related Questions