0

我目前正在使用此功能来创建和显示一个按钮。

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();
  }
}

我想创建一个函数,例如: void hide() 以便我可以在需要时删除或隐藏该函数,然后单击它。我应该如何处理这个?我基本上将所有内容都设置为空吗?删除它?

4

2 回答 2

2

我现在不能确定,因为您还没有发布实际的类定义,但我保证您可以扩展 java.awt.Button 或 javax.swing.JButton。

在这种情况下,您可以只使用 setVisible 方法:

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

这适用于扩展 java.awt.Component 的每个 GUI 组件。

在一个非常简单的例子中(这是一个单向的事情,因为你不能让按钮回来;))这看起来像:

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);
    }
}

在编写该示例时,我发现 java.awt.Component 甚至定义了一个方法“hide()”,但这被标记为已弃用,并提示使用 setVisible。

我希望这有帮助!

于 2013-11-13T17:25:26.693 回答
1

也许是一个简单的布尔值show包装显示语句......还有一个键或任何东西来toggle它。

喜欢:

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

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

您还需要包装按钮的功能。

于 2013-11-14T02:14:10.347 回答