【问题标题】:Java FX - How to use a button-with-an-image, inside an "if" condition?Javafx - 如何在“if”条件下使用带有图像的按钮?
【发布时间】:2016-09-15 15:35:41
【问题描述】:

这是我的代码,有些部分已经省略(比如imports、psvm等):

public class Proyect extends Application implements EventHandler{

    private HBox menu1() {
        Image food1 = new Image (getClass().getResourceAsStream("clipboard.png"));
        Button btnR = new Button ("R", new ImageView(food1));
    }

    @Override
    public void handle(Event event) {
        if(event.getSource() == btnR) {

        }
    }
}

问题是我的 IDE 说我在 if 语句中的“btnR”这件事上弄错了(它带有红色下划线)。

【问题讨论】:

  • btnR 在不同的范围内。如果您希望它可以从 handle() 访问,您需要将其设为类变量。

标签: java button javafx


【解决方案1】:

Button btnR 在方法menu1() 中定义。因此它不能在方法handle() 中访问。为什么不在类中将其定义为私有数据成员?

请使用以下逻辑:

public class Proyect extends Application implements EventHandler{

private Button btnR;

private HBox menu1() {
    Image food1 = new Image (getClass().getResourceAsStream("clipboard.png"));
    btnR = new Button ("R", new ImageView(food1));
}

@Override
public void handle(Event event) {
    if(event.getSource() == btnR) {

    }
}
}

【讨论】:

  • @Praven Vinny 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2014-10-14
  • 2013-03-17
  • 2015-07-17
  • 2020-10-01
  • 2021-11-06
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多