使按钮显示标签中的不同文本Javafx
问题描述:
我是Javafx的新手,我试图让一个按钮显示我在arrayList中存储的字符串。代码工作正常,但只显示一次,无论多少次点击它永远不会改变。使按钮显示标签中的不同文本Javafx
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
public class FXMLDocumentController {
public Label lblNext;
public Button btnNext;
int count = 0;
public void btnClick(){
ArrayList<String> words = new ArrayList<String>();
words.add("one");
words.add("two");
words.add("three");
words.add("four");
count=+1;
lblNext.setText(""+words.get(count));
}
}
以下是FXML代码。
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="321.0" prefWidth="412.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="memorizer.FXMLDocumentController">
<children>
<Label fx:id="lblNext" alignment="CENTER" layoutX="13.0" ``layoutY="10.0" minHeight="16" minWidth="69" prefHeight="244.0" prefWidth="386.0" text="Click Next To Begin" />
<Button fx:id="btnNext" layoutX="150.0" layoutY="265.0" mnemonicParsing="true" onAction="#btnClick" prefHeight="42.0" prefWidth="113.0" text="Next" />
</children>
</AnchorPane>
答
我想通了,我的方法是缺少一个行动事件。
public void btnClick(ActionEvent event);
答
它应该是
count += 1;
或类似的代替
count=+1;
东西这相当于
count=1;
即它总是分配相同的值,以count
这意味着索引阅读始终是相同的,因此文字永远不会改变...
注意,与4开始点击事件处理程序将启动造成IndexOutOfBoundsException
小号...
此外,如果您从列表中读取元素之前增加值,你会与第二启动而不是第一个元素。您可能希望交换的语句:
lblNext.setText(words.get(count));
count++; // shortened version of count+=1;
另外,FXML内``
部分是指文件不是格式良好的XML文件,因此必须以正确解析该文件被删除..
这没有什么区别 –
它对我很有效,它是我添加的唯一东西。 – Noppy