我目前正在使用此函数来创建和显示一个按钮。
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();
}
}
我想创建一个函数,例如: 无效隐藏() 这样我就可以在需要时在单击该功能后删除或隐藏该功能。我应该如何处理这个问题?我基本上将所有内容都设置为空吗?删除它?
最佳答案
我现在无法确定,因为您还没有发布实际的类定义,但我保证您要么扩展 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 代替。
希望这会有所帮助!
关于java - 如何创建一个删除按钮的函数[初学者],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19959662/